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

use*_*343 1 c++ stringstream

#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;
}
Run Code Online (Sandbox Code Playgroud)

转换对我不起作用.如果我将字符'4'或字符数组{'4','\ 0'}写入stringstream然后将其读出为int i,我就不会回复4.上述代码有什么问题?

Joh*_*ing 10

因为您将stringstream输入设置为仅输入 - 无输出.

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

 s >> i;
  bool b = s.fail();
  if( b )
      cerr << "WHOA DOGGIE!  WE BLOWED UP\n";
Run Code Online (Sandbox Code Playgroud)

在您的代码中,更改:

stringstream s(ios::in);
Run Code Online (Sandbox Code Playgroud)

至:

stringstream s;
Run Code Online (Sandbox Code Playgroud)