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