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()
是以什么来判断的?
天蓬老师2017-04-17 13:31:48
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