0

我正在尝试使用 sstream 读取一个由三个数字组成的字符串,但是当我尝试打印它们时,我得到了一个带有四个数字的错误输出。

代码:

#include <iostream>
#include <sstream>

using namespace std;

int main() {
    string a("1 2 3");

    istringstream my_stream(a);

    int n;

    while(my_stream) {
        my_stream >> n;
        cout << n << "\n";
    }
}

输出:

1
2
3
3

为什么与输入字符串中的三个数字相比,我在输出中得到四个数字?

4

2 回答 2

2

这里

while ( my_stream )

my_stream如果没有 I/O 错误,则可转换为bool并返回。true

请参阅:https ://en.cppreference.com/w/cpp/io/basic_ios/operator_bool

因此,在最后一次读取之后,还没有 I/O 错误,所以它再次迭代并且出现错误并且n在此语句中没有读入任何内容:

my_stream >> n;

并且,std::cout再次打印最后提取的值,即 3。

解决方案可能是在读入后直接检查 I/O 错误while(首选):

while ( my_stream >> n )
{
    std::cout << n << '\n';
}

或者,仅在使用读取成功时打印if

while ( my_stream )
{
    if ( my_stream >> n ) // print if there's no I/O error
    {
        std::cout << n << '\n';
    }
}

示例(现场):

#include <iostream>
#include <sstream>

int main()
{
    std::string a { "1 2 3" };

    std::istringstream iss{ a };

    int n {0};

    while ( iss >> n )
    {
        std::cout << n << '\n';
    }

    return 0;
}

输出:

1
2
3

相关:为什么是“使用命名空间标准;” 被认为是不好的做法?

于 2020-05-17T05:42:27.507 回答
0

在检查读数是否成功之前,您正在打印数据。

    while(my_stream) {
        my_stream >> n;

应该

    while(my_stream >> n) {

相关(似乎不重复,因为eof()这里没有使用):
c++ - 为什么 iostream::eof 在循环条件(即while (!stream.eof()))内被认为是错误的?- 堆栈溢出

于 2020-05-17T05:17:27.010 回答