c++ - stringstream 重复最后一个词

标签 c++

我正在尝试使用 stringstream 拆分字符串:

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main(){
    ifstream fp;
    string name;

    fp.open("in.txt");
    while (fp){
        string line;
        getline(fp, line);
        cout << line << endl;
        istringstream line_stream(line);

        while (line_stream){
            line_stream >> name;
            cout << name << " ";
        }
    }

    return 0;
}

这是 in.txt :

cat bat rat sat

这是我得到的输出:

cat bat rat sat
cat bat rat sat sat

getline() 函数中检索到的行是正确的,但在拆分过程中我得到了最后一个字两次。我不确定为什么会这样。

最佳答案

您正在使用 getline 的结果,而没有检查是否 它成功了。这是第一个错误(可能导致 带有您显示的代码的额外空行)。同样,你使用 line_stream >> name 的结果而不检查它是否 成功了;在这种情况下(因为 name 不是新建的 每次通过),你可能会得到之前阅读的 值(但在这两种情况下,字符串的内容都是 未指定)。

你必须永远在没有首先测试的情况下使用输入的结果 是否成功。最常见的做法(但 当然不是唯一的方法)是在条件中进行输入 循环的:

while ( std::getline( fp, line ) ) ...

while ( line_stream >> name ) ...

如果您仍想将变量的范围限制在 循环,你必须写:

while ( fp ) {
    std::string line;
    if ( std::getline( fp, line ) ) {
        //  rest of loop
    }
}

如果您(可以理解)反对修改全局 状态,你必须写:

std::getline( fp, line );
while ( fp ) {
    //  ...
    std::getline( fp, line );
}

虽然我认为有强有力的论据支持这一点, while ( std::getline( fp, line ) ) 习语无处不在, 其他任何事情都会引起读者怀疑的地方 为什么。

关于c++ - stringstream 重复最后一个词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17807634/

相关文章:

c++ - 为什么我的C++程序只能读取绝对目录而不能读取同一文件夹中的文件?

c++ - 更好地提升 asio deadline_timer 示例

c++ - 无法打开 lib python。 Panda3D 项目。 VS

c++ - 更少的内存使用

c++ - Foo &foo = Bar() 是合法的还是编译器问题

c++ - Eclipse GDB 找不到源文件

c++ - libcurl : output of network upload download speed is not accurate

C++打印执行的代码

c++ - 如何在 C++ 代码中链接 STL?

c++ - 如何使用 boost::asio io_service 异步运行函数