2017-02-03 46 views
-1

這是代碼...如何檢測控制檯輸入不是C++中的數字?

#include <iostream>  
#include <iomanip>  
#include <cmath>  
#include <math.h>  

using namespace std;  

void CorrectPercent(double Percent) { 

unsigned short int Error = 0; 
while (Error==0){ 

    cout << "\nEnter the annual interest rate (%):\t\t"; 
    cin >> Percent; 
do { 
     if (Percent <= 0) { 
      cout << endl << "Please enter a valid annual interest rate (%): "; 
      cin >> Percent; 
     } else if (isnan(Percent) == true) { 
      cout << endl << "Please enter a valid annual interest rate (%): "; 
      cin >> Percent; 
     } 
     else { 
      Error=1; 
     } 
    } while (Error == 0); 
    //Error++; 
}//while (Error == 0); 
} 


int main() 
{ 
double Percent; 
char Retry = 'Y'; 

do 
    { 
     cout << setprecision(2) << fixed; 
     system("cls"); 
     CorrectPercent(Percent); 
    } while (Retry == 'Y' || Retry == 'y'); 
return 0; 
} 

的CorrectPercent功能應該直到輸入一個有效的數值是保持運行。所以,問題是,我怎樣才能檢測到輸入是數字?只是爲了獲得更多信息,我正在使用Visual Studio 2015.

回答

-3

由於Percent被聲明爲double,cin >> Percent會在用戶輸入非數字數據時失敗。你可以用cin.fail()來檢測:

std::cin >> Percent; 
while (std::cin.fail()) { 
    std::cin.clear(); 
    std::cin.ignore(std::max<std::streamsize>()); 
    std::cout << "Please enter a valid number." << std::endl; 
    std::cin >> Percent; 
} 
+1

這是一個無限循環,如果它被輸入的話。 –

+0

@BaummitAugen哎呀...忘了重置...更好? –

+0

仍無限循環,壞的輸入仍在流中。 –

相關問題