0

Right now, I want to handle data file in the following format:

apple 1234
coke 2344 some
grape 2345 null
....

as some lines consist of 3 element while some other have 2,I want to use the expression as follows to get the first two elements in every line and make them into a map or hash_map,

...
 while(outClientFile>>name>>state)
pairs.insert(name,state);//
...

somehow,I figure out that it can not work because of the structure of fstream.so do you have any suggestions on this problem?

2
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by gshock2006
1
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>

using namespace std;

int main()
{
   //read in file
   ifstream read ( "c:/test.txt" );

   string line;

   while ( getline ( read, line, '\n' ) )
   { 
      vector <string> myStuff;
      stringstream ss ( line );
      string word;

      while ( ss >> word )
      {
         myStuff.push_back ( word );
      }
      //print out first two elements
      cout << myStuff[0] << "  " << myStuff[1] << endl;
   } 
   read.close();
   cin.get();
}

output

apple  1234
coke  2344
grape  2345
Votes + Comments
nice and silent..
0

thanks,buddy, it works.However,since I am completely new to cpp,could you explain a little more about the code for me,I hope I can grasp something from it. since you use the expression "while(ss>>word)" you just store the second element as string,but as I put first that I want to get the element and store them in a hash_map(or a map),say " name[id] " form,it turns out that I have to take another step to handle the output file, so do I have other methods to accomplish that.

....
      stringstream ss ( line );
      string word;

      while ( ss >> word )
      {
         myStuff.push_back ( word );
      }
      //print out first two elements
      cout << myStuff[0] << "  " << myStuff[1] << endl
...

output

apple  1234
coke  2344
grape  2345
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.