0

I'm trying to read a file word by word and do some implementation on each word. In future I want to know where was the position of each word. Position is line number and character position in that line. If character position is not available I only need to know when I'm reading a file when I go to the next line. This is the sample code I have now:

string tmp;
while(fin>>tmp){
     mylist.push_back(tmp);
}

I need to know when fin is going to next line?!

LihO
  • 41,190
  • 11
  • 99
  • 167
Bernard
  • 4,240
  • 18
  • 55
  • 88

2 Answers2

1

One simple way to solve this problem would be using std::getline, run your own counter, and split line's content into words using an additional string stream, like this:

string line;
int line_number = 0;
for (;;) {
     if (!getline(fin, line)) {
         break;
     }
     istringstream iss(line);
     string tmp;
     while (iss >> tmp) {
         mylist.push_back(tmp);
     }
     line_number++;
}
David G
  • 94,763
  • 41
  • 167
  • 253
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Thanks for your answer, how about position of the word in each line? Any solution? – Bernard Nov 05 '13 at 00:34
  • @Bernard This one is a little trickier, because multiple separators are treated as one. If an approximate position would be OK, you could add up the lengths of tmps as you go, adding one to the length on each step to account for spaces. The value would be exact only when a single space is used. A better approach would use string's find function of temp inside line: that would account for multiple separators as well. – Sergey Kalinichenko Nov 05 '13 at 00:44
1

"I need to know when fin is going to next line"

This is not possible with stream's operator >>. You can read the input line by line and process each line separately using temporary istringstream object:

std::string line, word;
while (std::getline(fin, line)) {

    // skip empty lines:
    if (line.empty()) continue;


    std::istringstream lineStream(line);
    for (int wordPos = 0; lineStream >> word; wordPos++) {
        ...
        mylist.push_back(word);
    }
}

just don't forget to #include <sstream>

LihO
  • 41,190
  • 11
  • 99
  • 167
  • Thanks for your answer, how about position of the word in each line? Any solution? – Bernard Nov 05 '13 at 00:33
  • In case you will need the position of each word at different parts of your program, maybe you could consider using `std::vector< std::vector >` instead, i.e. vector lines, where every line is vector of words. – LihO Nov 05 '13 at 00:43