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?

Member Avatar for iamthwee
#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
commented: nice and silent.. +1

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
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.