[C++] 关于stringstream ss.fail()的问题
高洛峰
高洛峰 2017-04-17 13:29:48
0
1
825
  int i = 0;
  getline(cin, s);
  ss.clear(); ss.str(s);
  while(!ss.fail()) 
    ss >> H[i++]; 

假如getline读入了1 2 3 4, 这段代码运行结束后, i的值为5. 这是为什么?
请问ss.fail()是以什么来判断的?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(1)
Peter_Zhu

May I ask ss.fail() how to judge?

is judged based on the status of ss and failbit of the badbit object.

i has a value of 5. Why is this?

Because after reading the last number 4, ss is still in a normal state, and an error will occur only if you try to read it again (i.e., the 5th loop). You can try entering a blank line and the value of i is 1.

Common practices are:

int i = 0;
getline(cin, s);
ss.clear(); ss.str(s);
while(ss >> H[i++]) { }

Reference

  • std::basic_ios::fail

  • std::basic_stringstream

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template