为什么 cin 中断时会发生变量? C++
Why happens to variable when cin breaks? C++
我有以下代码片段:
int a = 1;
double b = 3.14;
string c = "hi";
cin >> a >> b >> c;
cout << a << " " << b << " " << c << endl;
如果我输入 apple 11 tammy
,为什么它会显示:0 3.14 hi
而不是:1 3.14 hi
?
为什么a
的值在cin
坏掉的时候会改变?
Why does the value of a
change when cin
is broken?
这是自 C++11 以来 std::basic_istream::operator>> 的预期行为;如果提取失败,该值将设置为 0
.
If extraction fails, zero is written to value and failbit is set. If extraction results in the value too large or too small to fit in value, std::numeric_limits<T>::max()
or std::numeric_limits<T>::min()
is written and failbit flag is set.
注意设置failbit
后,下面的输入将不会执行;这意味着 b
和 c
将保持其原始值。
顺便说一句:在 C++11 之前,当提取失败时,该值将保持不变。
If extraction fails (e.g. if a letter was entered where a digit is expected), value is left unmodified and failbit is set.
改用字符串流。这是 link 详细解释同一问题的文章:
我有以下代码片段:
int a = 1;
double b = 3.14;
string c = "hi";
cin >> a >> b >> c;
cout << a << " " << b << " " << c << endl;
如果我输入 apple 11 tammy
,为什么它会显示:0 3.14 hi
而不是:1 3.14 hi
?
为什么a
的值在cin
坏掉的时候会改变?
Why does the value of
a
change whencin
is broken?
这是自 C++11 以来 std::basic_istream::operator>> 的预期行为;如果提取失败,该值将设置为 0
.
If extraction fails, zero is written to value and failbit is set. If extraction results in the value too large or too small to fit in value,
std::numeric_limits<T>::max()
orstd::numeric_limits<T>::min()
is written and failbit flag is set.
注意设置failbit
后,下面的输入将不会执行;这意味着 b
和 c
将保持其原始值。
顺便说一句:在 C++11 之前,当提取失败时,该值将保持不变。
If extraction fails (e.g. if a letter was entered where a digit is expected), value is left unmodified and failbit is set.
改用字符串流。这是 link 详细解释同一问题的文章: