0

我正在尝试编写一个在读取 txt 文件时会跳过最后一个单词的代码。我不确定如何在包括最后一行和它之前的空格的情况下输出该行。任何帮助将不胜感激,我是 C++ 新手。

4

1 回答 1

2

这是模拟输入的一种相当简单的方法:

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';
}   
于 2013-06-19T03:26:12.377 回答