【发布时间】:2015-11-04 10:48:08
【问题描述】:
我已经在 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;
}
【问题讨论】:
-
operator<<()会将age设置为其默认值(即在这种情况下为0)并在无法读取数字时覆盖-1。这是正常行为。 -
@πάνταῥεῖ 你的意思是
operator>>,对吧? -
en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt 引用:
since c++11: If extraction fails, zero is written to value and failbit is set -
但是,从一开始,我就说
age=-1,如果它没有读取任何内容,它应该输出-1。不应该吗? @πάνταῥεῖ -
@Angew 哎呀,当然。