2014-11-20 118 views
0

我新的C++和一些错误发生的事情,为什么INT返回0 - C++

基本上,我已经宣布了一个名为number变量,它是int类型。

如果我输入一个字符串,如ax...然后数目变得0。我不希望号码变成0,而是希望它被错误处理。

如何防止这是C++? ,这是我的源代码...

#include <iostream> 
using namespace std; 

int number; 

int main() { 
    cout << "Please input a number: "; 
    cin >> number; 
    cout << number << endl; 
    return 0; 
} 
+0

'if(!cin >> number)' – Borgleader 2014-11-20 20:48:46

+0

@CaptainObvlious不,它是C++ 11的行为,[请参阅我的问题](http://stackoverflow.com/questions/19522504/istream-行为改变失败) – Borgleader 2014-11-20 20:49:23

+0

你可以使用['cin.exceptions'](http://en.cppreference.com/w/cpp/io/basic_ios/exceptions)使其发生错误。仍然将它归零... – Deduplicator 2014-11-20 20:51:09

回答

2

您需要检查cin发生了什么:

if (cin >> number) { 
    cout << number << endl; 
} 
else { 
    cout << "error: I wanted a number." << endl; 
} 
+0

谢谢@Barry :),那么'double'输入呢?例如,如果我输入'9.5',然后输入数字='9',但是我还想要一个错误消息弹出 – 2014-11-20 20:53:39

+0

如果您需要完整的输入验证,然后正确的方式输入一个字符串,然后使用像正则表达式。 – Slava 2016-08-26 16:35:19

0

为此,您可以在临时存储字符串值,然后做一些转换成int和双:

#include <iostream> 
#include <string> 
#include <stdlib.h> //needed for strtod 
using namespace std; 
int main() { 
    string str; 
    cin >> str; //Store input in string 
    char* ptr; //This will be set to the next character in str after numerical value 
    double number = strtod(str.c_str(), &ptr); //Call the c function to convert the string to a double 
    if (*ptr != '\0') { //If the next character after number isn't equal to the end of the string it is not a valid number 
     //is not a valid number 
     cout << "It is not a valid number" << endl; 
    } else { 
     int integer = atoi(str.c_str()); 
     if (number == (double)integer) { //if the conversion to double is the same as the conversion to int, there is not decimal part 
      cout << number << endl; 
     } else { 
      //Is a floating point 
      cout << "It is a double or floating point value" << endl; 
     } 
    } 
    return 0; 
} 

请注意,全局变量是坏,他们写一个范围(一个函数或CLA内例如)