-3

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • You will learn how to do this [by following the practice examples in any C++ textbook](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). Unfortunately Stackoverflow is not a replacement for a C++ textbook, so you're directed to yours' for more information. – Sam Varshavchik Dec 29 '20 at 01:22
  • 1
    I would say for this a good `c++` solution would not be compatible with `c`. – drescherjm Dec 29 '20 at 01:27

1 Answers1

2

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.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111