如果输入类型与目标类型不同,"cin" 是否会将变量重置为某个默认值?
Does "cin" reset variable to some default value if input type differs from destination type?
我对 "cin" 的行为有疑问(我不明白)。我的 IDE 是 Windows OS 下的 Netbeans(使用 Cygwin)。
这是一个代码示例:
int main()
{
int temp = -1;
std::cin >> temp; // here user enters string of characters (string) or a single character
if (temp == 0)
std::cout << "temp = " << temp << ".\n";
if (temp == -1)
std::cout << "temp = " << temp << ".\n";
return 0;
}
如果我输入某种 character/string 字符,此代码将显示消息 temp = 0。这就像 char
到 int
的转换,并且转换总是以值 0.
结束
谢谢你能解释一下这个行为。
如果读取失败 operator>>
会将值设置为零 (cppreference):
If extraction fails, zero is written to value and failbit is set.
这是 std::basic_istream::operator>>
的预期行为;从C++11开始,如果提取失败,变量将被设置为0。在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. (until C++11)
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::max() or std::numeric_limits::min()
is written and failbit flag is set. (since C++11)
我对 "cin" 的行为有疑问(我不明白)。我的 IDE 是 Windows OS 下的 Netbeans(使用 Cygwin)。
这是一个代码示例:
int main()
{
int temp = -1;
std::cin >> temp; // here user enters string of characters (string) or a single character
if (temp == 0)
std::cout << "temp = " << temp << ".\n";
if (temp == -1)
std::cout << "temp = " << temp << ".\n";
return 0;
}
如果我输入某种 character/string 字符,此代码将显示消息 temp = 0。这就像 char
到 int
的转换,并且转换总是以值 0.
谢谢你能解释一下这个行为。
如果读取失败 operator>>
会将值设置为零 (cppreference):
If extraction fails, zero is written to value and failbit is set.
这是 std::basic_istream::operator>>
的预期行为;从C++11开始,如果提取失败,变量将被设置为0。在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. (until C++11)
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::max() or std::numeric_limits::min() is written and failbit flag is set. (since C++11)