stringstream复制最后一个字 [英] stringstream duplicates last word

查看:97
本文介绍了stringstream复制最后一个字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to split a string using 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()函数检索的行是正确的,我得到最后一个字两次。

The line retrieved from getline() function is right, but in the process of splitting I'm getting the last word twice. I'm not sure why is this happening.

推荐答案

您使用的结果 getline ,而不检查
是否成功。这是第一个错误(可能导致
一个额外的空行与您显示的代码)。同样,你使用
的结果 line_stream>> name ,而不检查它是否成功
;在这种情况下(因为 name 不是新构建的
每次通过),你可能会得到以前读取的
值,字符串的内容是
unspecified)。

You are using the results of getline without checking whether it succeeded. This is the first error (and probably results in an extra empty line with the code you show). Similarly, you use the results of line_stream >> name without checking whether it succeeded; in this case (because name is not newly constructed each time through), you may end up with the previously read value (but in both cases, the contents of the string are unspecified).

您必须从不使用输入结果,而无需先测试
是否成功。最常见的方式(但
肯定不是唯一的方法)是在循环的条件
中输入:

You must never use the results of input without first testing whether it succeeded. The most common way of doing this (but certainly not the only way) is to do the input in the condition of the loop:

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

while ( line_stream >> name ) ...

如果您仍想将变量的范围限制为
循环,写:

If you still want to limit the scope of the variable to the loop, you'd have to write:

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

如果你在一个条件中修改了全局
状态,你应该写:

If you have (understandably) something against modifying global state in a condition, you'd have to write:

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

虽然我认为有强烈的理由支持这个,
while(std :: getline(fp,line)) idiom是普遍存在的,到
其他任何事情会让读者猜想
为什么。

While I think that there are strong arguments in favor of this, the while ( std::getline( fp, line ) ) idiom is ubiquitous, to the point where anything else will cause the reader to wonder why.

这篇关于stringstream复制最后一个字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆