stringstream:为什么这段代码不返回 4?

stringstream: Why isn't this code returning 4?

本文关键字:返回 代码 为什么 段代码 stringstream      更新时间:2023-10-16
#include <iostream>
#include <sstream>
using namespace std;
int get_4()
{
  char c = '4';
  stringstream s(ios::in);
  s << c;
  int i;
  s >> i;
  return i;
}
int main()
{
  cout << get_4() << endl;
}

转换对我不起作用。如果我将字符"4"或字符数组 {'4','\0'} 写入字符串流,然后将其读出到 int i,则不会返回 4。上面的代码有什么问题?

因为您将stringstream设置为仅输入 - 没有输出。

如果您在尝试提取int后检查fail()位,您会发现它不起作用:

 s >> i;
  bool b = s.fail();
  if( b )
      cerr << "WHOA DOGGIE!  WE BLOWED UPn";

在代码中,更改:

stringstream s(ios::in);

自:

stringstream s;