gpt4 book ai didi

c++ - C++ 中变量的默认值使用 cin >>

转载 作者:可可西里 更新时间:2023-11-01 18:26:18 30 4
gpt4 key购买 nike

我在 CodeBlocks IDE 中用 C++ 编写了这段代码,但是当我运行它时,如果它没有读取数字,它不会给我 -1,它会给我 0。代码有问题吗?

#include "iostream"

using namespace std;

int main()
{
cout<<"Please enter your first name and age:\n";
string first_name="???"; //string variable
//("???" means "don't know the name")
int age=-1; //integer variable (-1 means "don't know the age")
cin>>first_name>>age; //read a string followed by an integer
cout<<"Hello, " <<first_name<<" (age "<<age<<")\n";

return 0;
}

最佳答案

std::basic_istream::operator>> 的行为已从 C++11 更改。从 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.

请注意,直到 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.

可以通过std::basic_ios::fail查看结果或 std::basic_ios::operator!并自行设置默认值。比如,

string first_name;
if (!(cin>>first_name)) {
first_name = "???";
cin.clear(); //Reset stream state after failure
}

int age;
if (!(cin>>age)) {
age = -1;
cin.clear(); //Reset stream state after failure
}

cout<<"Hello, " <<first_name<<" (age "<<age<<")\n";

另请参阅:Resetting the State of a Stream

关于c++ - C++ 中变量的默认值使用 cin >>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33519876/

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