2013-09-11 137 views
0

這是一個程序,用戶輸入5個分數,程序計算平均分數和分數。 但是,當用戶輸入字符串(字母)而不是數字時,它應該顯示一個錯誤。我該怎麼做呢?C++如何檢查雙數字是否作爲字母輸入

#include <iostream> 

using namespace std; 

int main() 
{ 
double dblMarkOne; 
double dblMarkTwo; 
double dblMarkThree; 
double dblMarkFour; 
double dblMarkFive; 
double dblAverage; 
string strGrade; 

cout<<"Enter your first mark: "; 
cin>>dblMarkOne; 

while (dblMarkOne < 0 || dblMarkOne > 100) 
{ 
    cout << "Enter a valid test score within 1 to 100. "; 
    cout << "Enter your first mark: "; 
    cin >> dblMarkOne; 
} 
+1

類似於這一個http://stackoverflow.com/questions/18728754/checking-input-value-is-an-integer – brunocodutra

回答

0

下面是一個簡單的解決方案。我相信你可以稍微調整一下以提高速度。

#include <iostream> 
#include <stdlib.h>  /* atoi */ 

using namespace std; 

bool isDouble(char a[]); 

int main() 
{ 
    double dblMarkOne;  
    char a[10]; 

    cout<<"Enter your first mark: "; 
    cin >> a; /* read it as a char array */ 

    if(isDouble(a)){  
    dblMarkOne = atof(a); 
    cout << dblMarkOne; 
    } 
    else 
    { 
    cout << "not a double"; 
    } 
} 

bool isDouble(char a[]) 
{ 
    int i = 0; 

    while(a[i] != 0) 
    { 
    if(!(isdigit(a[i]) || a[i] == '.')) 
    { 
     return false;  
    } 
    i++; 
    } 
    return true; 
} 
+0

如果在輸入是'1.1.1'? – thefourtheye

相關問題