2014-11-20 117 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內例如)