> a >> b >> c; cout -6ren">
gpt4 book ai didi

c++ - 为什么 cin 中断时会发生变量? C++

转载 作者:搜寻专家 更新时间:2023-10-30 23:53:27 27 4
gpt4 key购买 nike

我有以下代码片段:

    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

为什么cin被破坏时a的值会改变?

最佳答案

Why does the value of a change when cin is broken?

这是 std::basic_istream::operator>> 的预期行为自 C++11 起;如果提取失败,该值将设置为 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之后被设置后,将不会执行以下输入;这意味着 bc将保持其原始值。

顺便说一句:在 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.

关于c++ - 为什么 cin 中断时会发生变量? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41031094/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com