Reputation: 195
I am reading a table from a file which looks like this:
80 Sunny false 90 Play
75 Rainy true 88 Don't play
...
I'm using ifstream() and the thing is that I need the value of the last column (Play/Don't play) to initialize each of the previous variables. So is there a way to get the last element of a line first, and then I can read other elements from the beginning? Or alternatively, is there a way to read a line from the backwardly?
Edit0: So what I did is reading in the whole line to get the last variable and then loop through all the previous variables to initialize them. However, this makes the performance suffer a lot. So I'm seeking for a faster way to do it.
Edit1: So each variable is stored as a struct which also contains the last variable. After reading the 1st line I shall get an array of structs like this:
(80,Play) (Sunny,Play) (false,Play) (90,Play)
And in order to initialize these structs (or to set the second value of them), I need to know the last variable.
Edit2: Sorry I forgot to add that "Don't play" can also be "Don't_play", it doesn't have to have a space in it.
Upvotes: 0
Views: 315
Reputation: 409472
Read an integer, a string, a boolean and another integer, then throw them all away and use std::getline
to read the rest of the line.
After your edit.
You don't need the last part (the "Play"/"Don't play" strings) to create four different structures, you can create and partially initialize them, and then read the last part and finish the structure initialization.
So read the first four entries as normal, but save them into the structures you have. Then read the "Play"/"Don't play" string using std::getline
, and use that to finish the initialization of the structures.
To be a little more fail-safe, you could first read the whole line into a string using std::getline
, put the string into an std::istringstream
and read each element from the string stream.
Upvotes: 4
Reputation: 5231
You can read the last element of a line with this kind of solutions :
std::string last_line_word_1(std::istream& in)
{
std::string line;
std::getline(in, line);
std::size_t last_pos = line.find_last_of(' ');
if(last_pos == std::string::npos)
last_pos = 0;
else
++last_pos;
return line.substr(last_pos, line.length() - last_pos);
}
std::string last_line_word_2(std::istream& in)
{
std::string line;
std::getline(in, line);
std::reverse(line.begin(), line.end());
std::istringstream iss(line);
std::string word;
iss >> word;
std::reverse(word.begin(), word.end());
return word;
}
Upvotes: 1