C ++:未收到预期的输出

时间:2019-03-13 11:40:53

标签: c++ input output

我正在尝试从我的教程书中检查C ++代码。我已经使用CodeBlocks IDE编写了此代码:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
/*...*/
using namespace std;
/*...*/
int main (void){

    cout << "Please enter name and age: \n\n:>";
    string _sInput = "";
    int _intInput = -1;
    cin >> _sInput >> _intInput;
    cout << "Hello " << _sInput << "!\n";
    cout << "You have aged " << _intInput << " years.";
}

根据Stroustrup先生在书中讨论的内容,现在我给变量_intInput设置了一个初始值,如果我输入错误的数据James Boy,我应该会收到一个输出像这样:

Hello James!

You have aged -1 years.

但是我得到的是You have aged 0 years.,就像我没有给出初始值的时间一样。
我的代码有什么问题还是什么?!

2 个答案:

答案 0 :(得分:2)

由于C ++ 11,从istream读取整数或浮点数失败时,目标变量设置为0。有关更多信息,请参见this (cppreference.com)this (stack overflow.com)

这意味着您不能使用哨兵值来检测解析错误,而必须使用例如fail() method来检查是否存在某些错误。

答案 1 :(得分:2)