【问题标题】:sstream string wrong outputsstream 字符串错误输出
【发布时间】:2020-05-17 04:57:08
【问题描述】:

我正在尝试使用 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

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

【问题讨论】:

  • while(my_stream) -> while(my_stream &gt;&gt; n) { cout ... }
  • 那是错误的。已删除。

标签: c++ sstream


【解决方案1】:

这里

while ( my_stream )

my_stream 可转换为 bool 并在没有 I/O 错误时返回 true

见:https://en.cppreference.com/w/cpp/io/basic_ios/operator_bool

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

my_stream >> n;

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

解决办法可以是读入while后直接检查I/O错误(首选):

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';
    }
}

示例 (live):

#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

相关:Why is "using namespace std;" considered bad practice?

【讨论】:

    【解决方案2】:

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

        while(my_stream) {
            my_stream >> n;
    

    应该是

        while(my_stream >> n) {
    

    相关(似乎不重复,因为这里没有使用eof()):
    c++ - Why is iostream::eof inside a loop condition (i.e. while (!stream.eof())) considered wrong? - Stack Overflow

    【讨论】:

      猜你喜欢
      • 2018-09-12
      • 1970-01-01
      • 2017-02-26
      • 2014-03-08
      • 1970-01-01
      • 1970-01-01
      • 2020-11-30
      • 2014-02-22
      • 1970-01-01
      相关资源
      最近更新 更多