0

I'm trying to write a code that will skip the last word while reading txt file. I am not sure how to go about outputting the line without including the last line and the space before it. Any help would be appreciated, I'm new to c++.

1 Answers1

2

Here's a fairly straightforward way with simulated input:

for (std::string line : {"hello im joe", "abc def", "123", "1 2 3 4 5"}) {
    auto pos = line.find_last_of(' '); //find last space

    if (pos == std::string::npos) {
        continue; //don't print anything if not found
    }

    //print substring from beginning to space position
    std::cout << line.substr(0, pos) << '\n';
}   
chris
  • 60,560
  • 13
  • 143
  • 205
  • Note, the above syntax will only work if your compiler supports [range-based for loops](http://en.wikipedia.org/wiki/C%2B%2B11#Range-based_for_loop). – Anthony Jun 19 '13 at 04:13
  • @anthony-arnold, That's just for simulated input since Coliru doesn't do input (it shows which inputs work pretty nicely, though). It would probably be `for (std::string line; std::getline(std::cin, line);)`. – chris Jun 19 '13 at 04:16