I am trying to write program for parsing and processing text file.
After not being successful with implementing sscanf i decided to try stringstream.
I have vector of strings containing data separated by spaces, like:
some_string another_string yet_another_string VARIABLE_STRING_NO_1
next_string
I wrote code and expected result would be:
Counter: 4
Variable number 1 : VARIABLE_STRING_NO_1
Variable number 2 : VARIABLE_STRING_NO_2
Variable number 3 : VARIABLE_STRING_NO_3
Variable number 4 : VARIABLE_STRING_NO_4
but instead i get:
Counter: 4
Variable number 1 : VARIABLE_STRING_NO_1
Variable number 2 : VARIABLE_STRING_NO_1
Variable number 3 : VARIABLE_STRING_NO_1
Variable number 4 : VARIABLE_STRING_NO_1
Can anyone push me in right direction please? (eg. use other container instead of vector, change method to… etc)
Also what if VARIABLE_STRING contains 2 sub-strings with space inbetween? That is possible in my data.
Sample code:
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
vector<string> vectorOfLines, vectorOfData;
vectorOfLines.push_back("some_string another_string yet_another_string VARIABLE_STRING_NO_1 next_string");
vectorOfLines.push_back("some_string another_string yet_another_string VARIABLE_STRING_NO_2 next_string");
vectorOfLines.push_back("some_string another_string yet_another_string VARIABLE_STRING_NO_3 next_string");
vectorOfLines.push_back("some_string another_string yet_another_string VARIABLE_STRING_NO_4 next_string");
string data = "", trash = "";
stringstream token;
int counter = 0;
for( int i = 0; i < (int)vectorOfLines.size(); i++ )
{
token << vectorOfLines.at(i);
token >> trash >> trash >> trash >> data >> trash;
vectorOfData.push_back(data); // wrong method here?
counter++; // counter to test if for iterates expected times
}
cout << "Counter: " << counter << endl;
for( int i = 0; i < (int)vectorOfData.size(); i++ )
{
cout << "Variable number " << i + 1 << " : " << vectorOfData.at(i) << endl;
}
return 0;
}
Excuse my newbie question but after trying different approaches for last 5 days, I got to the point of swearing and getting discourages to continue learning.
Yes I’m very new to C++.
I’ve successfully done the same program in PHP (being total newbie in that too) and it seems like C++ is much, much harder to do.
You want to reset you string stream after reading an individual. From the looks of it, the string stream you are using goes into a fail state. At this point it won’t except any further input until the state gets
clear(). Also, you should always verify that you read was successful. That is, I would start the body of your loop something like this:I would also just use an
std::istringstream.