为什么int返回0 - C ++

时间:2014-11-20 20:48:02

标签: c++ error-handling

我是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;
}

2 个答案:

答案 0 :(得分:2)

您需要检查cin中发生的事情:

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

答案 1 :(得分:0)

为此,您可以将值存储在临时字符串中,然后对int和double进行一些转换:

#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;
}

请注意全局变量很糟糕,将它们写在范围内(例如函数或类)