【问题标题】:Last of word of each line needs to be skipped?每行的最后一个单词需要跳过吗?
【发布时间】:2013-06-15 10:59:50
【问题描述】:

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

【问题讨论】:

  • 你的意思是要逐行读取一个文件并输出没有最后一个单词的行吗?
  • 是的,正是我需要的,谢谢!
  • 显示你写的代码

标签: c++ getline genfromtxt


【解决方案1】:

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

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';
}   

【讨论】:

  • 注意,上面的语法只有在你的编译器支持range-based for loops时才有效。
  • @anthony-arnold,这只是用于模拟输入,因为 Coliru 不进行输入(但它显示了哪些输入工作得很好)。可能是for (std::string line; std::getline(std::cin, line);)
猜你喜欢
  • 2012-03-15
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
  • 2015-01-10
  • 2019-01-28
  • 2022-01-05
  • 2011-10-16
  • 1970-01-01
相关资源
最近更新 更多