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?
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".
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, ',')