为什么stringstream不移动到下一组字符时cout? [英] Why does stringstream not move to next set of characters when cout?

查看:112
本文介绍了为什么stringstream不移动到下一组字符时cout?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

string inputLine = "1 2 3";
stringstream stream(inputLine);

// Case One
int x, y, z;
stream >> x;
stream >> y;
stream >> z;
// x, y, z have values 1, 2, 3

// Case Two
cout << stream << endl;
cout << stream << endl;
cout << stream << endl;
// All 3 print out 1

对于上面的代码,

实际代码:
我正在编译这个在mac上使用g ++

Actual code: I'm compiling this on a mac using g++

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

using namespace std;

int main(int argc, char *argv[])
{
    string inputLine = "1 2 3";

    stringstream stream(inputLine);

    // Case One
    int x, y, z;
    stream >> x;
    stream >> y;
    stream >> z;
    // x, y, z have values 1, 2, 3

    // Case Two
    cout << stream << endl;
    cout << stream << endl;
    cout << stream << endl;
}


推荐答案

是由于您的标准库实现中的错误(#56193

This shouldn't compile but does due to a bug (#56193) in your standard library implementation, which is not fully C++11-compliant.

流正在转换为 bool 其状态; 正在为 true 正在列印 1

The stream is converting to a bool representing its state; cout is printing 1 for true.


  • 更改整数,您将看到输出仍为 1

  • 或者,将 std :: boolalpha 添加到 std :: cout 将会看到 true ,而不是 1

  • Change your integers and you'll see the output is still 1.
  • Or, add std::boolalpha to std::cout and you'll see true instead of 1.

它的关键是你的 std :: cout<< stream 实际上不打印与流缓冲区的内容有关的任何内容。这不是如何从数据流中提取数据。

The crux of it is that your std::cout << stream is not actually printing anything relating to the contents of the stream buffer. That's not how you extract data from a stream.

这篇关于为什么stringstream不移动到下一组字符时cout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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