about stringstream, reading from file

Hi,

I want to read data from a file and store them in two variables, and I wondered if it was actually necessary to use stringstream in this case. (can't test my code atm...). The data are separated by ',' in the file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
	ifstream in{filename};
while (getline(in, line)) {
        stringstream ss{line};
        
        string string_1;
        string string_2;

        
		getline(ss, string_1, ',');
		getline(ss, string_2, ',');
// or could I just have 
// getline(in,string_1,',');
// getline(in,string_2,','); 
// instead?
Hello Pecvx,

Post the input file or at lease a fair sample so everyone can see what you are working with.

I do not see any benefit in using string stream at the moment, until I see the input file.

The "getline"s that are commented should work just fine. Although for "string_2" i would leave off the (, ',') part as it would leave the new line as being the next character to be read.

If your file is actually:

string_1,string_2,\n
string_1,string_2,\n


Then you would have to read the new line before you continue to the second line in the file.

If the file is:

string_1,string_2\n
string_1,string_2\n


Then reading "string_2" would be getline(in, string_2); as the default for the third parameter is a "\n".

Hope that helps,

Andy
It's not necessary, but perhaps easier (especially if you want to detect if a line has the wrong number of values).
Thank you,

the format of the text file is on the form.

string_1,string_2\n
string_1,string_2\n


for the entire file. So I guess

1
2
getline(in,string_1,',');
getline(in,string_2); //read until line shift  


would be the best?

what if it was actually on the form

string_1,string_2,\n
string_1,string_2,\n


something like?
1
2
3
4
string line_shift; //string for line shift
getline(in,string_1,',');
getline(in,string_2,','); 
getline(in, line_shift);

Hello Pecvx,

Yes that will work. Although I am more likely to call it "junk" instead of "shift" as it is something that you want to read and through away.

Otherwise your first guess would work for "string_2" being followed by a "\n".

ANdy
Thanks.

Do you have any good examples on where stringstream is useful?
If your file has two comma separated strings in each line, perhaps you could consider this scheme:
- read a line by std::getline(myfile, a_string)
- initialize a std::istringstream by “a_string”
- read from that std::istringstream again by means of std::getline():
std::getline(my_istringstream, my_string, ',')

This way you could easily get rid of the comma.
Topic archived. No new replies allowed.