我已经在CodeBlocks IDE的C++中编写了这段代码,但是当我运行它时,如果它不读取数字,它不会给我-1,它会给我0.代码有问题吗?使用cin的C++变量的默认值>>
#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;
}
的'操作符<<()'将设置'age'到它的默认值(即'0'在这种情况下),并覆盖'-1'当它不能读取一个数字。这是正常的行为。 –
@πάνταῥεῖ你的意思是'operator >>',对吧? – Angew
http://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt Quote:'自C++ 11:如果提取失败,零写入值和失败位被设置' – bolov