在C++中读到一行的结尾

Pov*_*las 5 c++ file

我有这样的文本文件:

Sting Another string 0 12 0 5 3 8
Sting Another string 8 13 2 0 6 11

而且我想知道有多少数字.我认为我最好的选择是使用while类型循环,条件结束计数然后另一行开始,但我不知道如何在一行结束时停止读取.

感谢您提前的帮助;)

Ren*_*ter 11

将您的input流分成几行

std::string line;
while (std::getline(input, line))
{
  // process each line here
}
Run Code Online (Sandbox Code Playgroud)

要将一行拆分为单词,请使用stringstream:

std::istringstream linestream(line); // #include <sstream>
std::string word;
while (linestream >> word)
{
  // process word
}
Run Code Online (Sandbox Code Playgroud)

您可以为每个单词重复此操作以确定它是否包含数字.由于您没有指定您的数字是整数还是非整数,我假设int:

std::istringstream wordstream(word);
int number;
if (wordstream >> number)
{
  // process the number (count, store or whatever)
}
Run Code Online (Sandbox Code Playgroud)

免责声明:这种方法并不完美.它会检测单词开头的"数字" 123abc,它也会允许输入格式string 123 string.这种方法也不是很有效.