【发布时间】:2011-10-24 05:30:13
【问题描述】:
我有一个这样的文本文件:
Sting 另一个字符串 0 12 0 5 3 8
刺另一根弦 8 13 2 0 6 11
我想数一数那里有多少个数字。我认为我最好的选择是使用带有条件的 while 类型循环来结束计数,然后另一行开始,但我不知道如何在一行的末尾停止阅读。
提前感谢您的帮助;)
【问题讨论】:
-
到目前为止你有什么?
我有一个这样的文本文件:
Sting 另一个字符串 0 12 0 5 3 8
刺另一根弦 8 13 2 0 6 11
我想数一数那里有多少个数字。我认为我最好的选择是使用带有条件的 while 类型循环来结束计数,然后另一行开始,但我不知道如何在一行的末尾停止阅读。
提前感谢您的帮助;)
【问题讨论】:
将您的 input 流分成几行
std::string line;
while (std::getline(input, line))
{
// process each line here
}
要将一行拆分为单词,请使用字符串流:
std::istringstream linestream(line); // #include <sstream>
std::string word;
while (linestream >> word)
{
// process word
}
您可以对每个单词重复此操作,以确定它是否包含数字。由于您没有指定您的数字是整数还是非整数,我假设int:
std::istringstream wordstream(word);
int number;
if (wordstream >> number)
{
// process the number (count, store or whatever)
}
免责声明:这种方法并不完美。它将检测诸如123abc 之类的单词开头的“数字”,它还将允许诸如string 123 string 之类的输入格式。而且这种方法效率不高。
【讨论】:
为什么不使用getline()?
【讨论】:
行尾由 '\n' 字符表示。 当遇到'\n'时,在你的while循环中放置一个条件来结束
【讨论】: