0
void fill() { ifstream fin; fin.open(File); if (!fin) { throw std::runtime_error("unable to open file"); } char line[maximumCodeLine]; std::stringstream stream; string letter; string code; while(readline(fin, line, maximumCodeLine, '\n')) { string str = string(line); stream.str(str); stream >> letter >> code; cout << letter << endl; cout << code << endl; // basically what i want to do finally // create some object like --> object myObj(letter, code); } } bool readline(ifstream &fin, char *line, int linesize, char delim) { if (fin.eof()) return false; fin.getline(line, linesize, delim); if (!fin.good()) return false; int last = strlen(line) - 1; if (line >= 0 && line[last] == '\r') line[last] = '\0'; return true; } 

I have text file containing the following

abc 1234
ass 2345
dfd 3455

Basically, I want to create object taking two string parameters. Then I would get two words on the line of the text file and pass them into the object.

But when I print out the letter and code each time stream changes its string value, I get

abc 1234 abc 1234 abc 1234

It means that letter and code value does not change.

I think stream >> code and stream >> letter has problem because I confirmed that the stream itself changes its string value during the while loop

How can I get the next word???

4
  • do stream.clear(); before stream.str(str); Commented May 19, 2016 at 10:39
  • but why does it print the last twice ?? any idea? Commented May 19, 2016 at 10:45
  • i have got dfd 3455 dfd 3455 Commented May 19, 2016 at 10:45
  • Check the contents of line in the last iteration, I suspect it's an empty line. You should always check if your stream extractions were successful: if(stream >> letter >> code) { /* success */ } Commented May 19, 2016 at 10:59

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.