0

Here is an example used for parsing a text file and the problem is last string at a line always get double outputed if i declare the "string parm" outside the inner while loop (This only happends when some space characters appears in the end of each line in "source.txt", if not everything works well). I can fix this by deleting the appended space character in "source.txt" or by declaring the "string parm" inside the inner while loop, but i still can't figure out the reason cause double output, any ideas ?

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>

using namespace std;

void main(int argc, char* argv[])
{
   string f_string = "source.txt";

   ifstream inputFile(f_string, ifstream::in);

   char line[1024];

   while(inputFile.getline(line, 1023))
   {
      stringstream ss(stringstream::in | stringstream::out);
      ss.str(line);

      string parm;   // final string will preserved ???

      while(!ss.eof())
      {
         //string parm;   final string won't get double output if declare here ...

         ss >> parm;
         cout << parm << endl;

         if(parm.compare("value") == 0)
            cout << "Got value." << endl;
      }

      cout << endl;
   }
}

with source.txt like this:

1st name_1 value    
2nd name_2 value    
3rd name_3     

if some space characters appears in the end of each line, i got this:

1st
name_1
value
Got value.
value
Got value.

2nd
name_2
value
Got value.
value
Got value.

3rd
name_3
name_3

if not or if "string parm" declared inside the inner while loop, i got a more reasonable result:

1st
name_1
value
Got value.

2nd
name_2
value
Got value.

3rd
name_3
abelenky
  • 58,532
  • 22
  • 99
  • 149
Seila
  • 61
  • 3
  • Have you stepped through your code in a debugger? – Drew Dormann Apr 04 '13 at 03:39
  • Change this: `while(!ss.eof())` to this: `while (ss >> parm)` and remove the extraction in the loop, then [read this Q&A for why](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). – WhozCraig Apr 04 '13 at 03:41

1 Answers1

1

Change the code to as follows:

while(ss >> parm)
{
   cout << parm << endl;

   if(parm.compare("value") == 0)
        cout << "Got value." << endl;
}

The problem I suspect is with while(!ss.eof()). See Why is iostream::eof inside a loop condition considered wrong? for a detailed explanation.

//string parm;   final string won't get double output if declare here

If you declare string parm inside the loop, you get an empty string every time it loops. When ss >> parm fails, nothing will be read into the string and it outputs an empty string.

Community
  • 1
  • 1
Jesse Good
  • 46,179
  • 14
  • 109
  • 158