I have a .txt file that contains:
Gabriel 18 2002
Joseph 89 1931
How can I read the last column of the first line? Like 2002
I don't know how I can do that with C++, in Shell programming have the sed and awk
I have a .txt file that contains:
Gabriel 18 2002
Joseph 89 1931
How can I read the last column of the first line? Like 2002
I don't know how I can do that with C++, in Shell programming have the sed and awk
In C++ you'd normally do this by reading the entire line, finding (for example) the last space or tab character in the line, and then creating a substring containing the data after that:
std::getline(infile, line);
int pos = line.find_last_of(" \t");
std::string last_column;
if (pos == std::string::npos)
// wasn't found--process entire string
last_column = line;
else
last_column = line.substr(pos+1);
There's (at least) one more detail you may need to deal with. You may need to deal with your string having trailing white-space characters. For example, if it contained "Gabriel 18 2002 "
, the find_last_of
would find that trailing space, and treat what's after it (nothing) as the last column. If this is possible in your input, you'll probably want to add a trim
function to remove any trailing white space before trying to find the last column.