Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Read only 1 line with Multiple strings

Status
Not open for further replies.

dsanow92

Programmer
Nov 15, 2005
3
0
0
US
I'm reading a .txt with multiple lines of text. I will need to compare the first word on every line with the words that follow, until a new line is started. I will then do the same thing.
I'm stuck trying to read only one line of strings at a time. I keep reading all the string in every while loop I create.
 
Use getline to read in the line, then put that line into a stringstream so you can read in each word one at a time.
Code:
std::string line;
while (std::getline(inFile, line))
{
  std::string word; // requires <string>
  std::istringstream istr(line); // requires <sstream>
  while (line >> word)
  {
    // use word
  }
}
Alternatively, you can read each word in one at a time and then peak at the next character in the stream to see if it is a newline. If it is, then start a new line.
 
I don't think the while (line >> word) is supposed to have be ">>". I changed it to ">" and it runs. But why on earth would it be jumping out of the program early saying a single word is larger the line?
 
No, it is supposed to be ">>". Were you having a problem with it? Do you understand what is going on in that code?

A stringstream is like a filestream or a console input stream (cin). It reads data from the string you initialize it with. I initialized it with line, which is a string containing a line from the file. I then used operator>> to read one word at a time from the line, just like you probably did with inFile.

I put that in the while loop, because you don't know how many words are in the line. The while loop will keep running until it reaches the end of the line, because if the read from operator>> fails, it sets the stream to a fail state and the return value of operator>> evaluates to false. Meanwhile, each time through the loop the word variable is already assigned the next word in the line for you to do your processing with.

If you need to process the first word in the line differently, then your code will look a little different. That example was just to give you an idea.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top