extract words from file with stringstream

I want to read a file:
word_1 word_2
word_1 word_2
word_1 word_2
..

extracting word_1 and word_2 with stringstream.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main(){
  stringstream b,x;
  fstream file;
  string n="prova.txt";
    file.open(n.c_str(),ios::in);
    if(file.is_open()) {
        while (!file.eof()) {
            getline(file, line);
            b << line;
            cout << word << " ";
            x << line;
            x >> word;
            cout << word << " " << endl;
        }
    }
    return 0;
}

doesn't work
Why not just use the >> file op?

Edit: if you already know that the line will only have the two words, then the stringstream is unnecessary, but if you do want to use the string stream, you have to use the .str() function to set the buffer of b to line or the buffer of x to line. b.str(line); /* or */ x.str(line);
Last edited on
@ema897, I'm inclined to agree with @highwayman.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
   string filename = "prova.txt";
// ifstream in( filename );                    // when used in anger
   stringstream in( "wordA wordB\n"            // for the purposes of demonstration
                    "wordC wordD\n"
                    "wordE wordF\n" );
                    
   for ( string a, b; in >> a >> b; )
   {
      cout << a << " " << b << '\n';
   }
}



If you are determined to read whole lines before breaking them up, then keep the relevant quantities in a very local scope.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
   string filename = "prova.txt";
// ifstream in( filename );                    // when used in anger
   stringstream in( "wordA wordB\n"            // for the purposes of demonstration
                    "wordC wordD\n"
                    "wordE wordF\n" );
   string line;                    
   while ( getline( in, line ) )
   {
      string a, b;
      stringstream( line ) >> a >> b;
      cout << a << " " << b << '\n';
   }
}



Whatever you do, don't use .eof() to test for end-of-file!
Last edited on
thanks.
Topic archived. No new replies allowed.