2016-12-02 147 views
-1

我想驗證雙數據類型的輸入,我已經部分成功了,因爲如果用戶輸入的第一個內容是字母,它將輸出錯誤消息,但是如果用戶輸入了編號在開始然後程序接受它,但它不應該。有想法該怎麼解決這個嗎?這裏是我到目前爲止的代碼:雙C++驗證無法正常工作

void circleArea(double pi)               
{ 
    double radius = 0.0; 
    bool badInput; 

    do 
    { 
     cout << "*================*\n"; 
     cout << " Area of a circle\n"; 
     cout << "*================*\n\n"; 
     cout << "Please enter the radius of your circle (numerics only):\n\n"; 
     cin >> radius; 

     badInput = cin.fail(); 
     cin.clear(); 
     cin.ignore(numeric_limits<streamsize>::max(), '\n'); 
    } while (badInput == true); 

    system("CLS"); 
    cout << "The area of your Circle is:\n\n" << radius*radius*pi << "cm^2" << endl << endl;  
    exitSystem(); 
} 
+1

_「但是,如果用戶在一開始那麼程序接受它,輸入一個號碼,雖然它不應該」 _你能詳細說明一下嗎? 「雙」值自然會帶數字? –

+0

好吧,所以如果輸入是像「5bffhds」(數字作爲第一件事)那麼該程序將不會認爲它是失敗的cin,而它是。如果輸入類似「gfsd3fdj」,驗證工作正常。 – PinkieBarto

+0

將輸入解析爲字符串塊,並使用'stod()'進行轉換。 –

回答

0

一個典型的成語是在if語句讀取值:

cout << "*================*\n"; 
cout << " Area of a circle\n"; 
cout << "*================*\n\n"; 
cout << "Please enter the radius of your circle (numerics only):\n\n"; 
if (!(cin >> radius)) 
{ 
    cerr << "Invalid input, try again.\n"; 
} 
else 
{ 
    // radius is valid 
} 

這不處理一個數字,後跟一個字母或無效符號的情況下,如「1.23A」或「1#76」。對於這些情況,您必須以字符串的形式讀取文本並執行更詳細的解析。

0

另一種可能性是,使用正則表達式來檢查輸入的字符串是否是一個字符串!

// Example program 
#include <iostream> 
#include <string> 
#include <boost/regex.hpp> 
#include <boost/lexical_cast.hpp> 

const boost::regex is_number_regex("^\\d+(()|(\\.\\d+)?)$"); 
//If I didn't make a mistake this regex matches positive decimal numbers and integers 
int main() 
{ 
    double radius; 
    std::string inputstring; 
    std::cin >> inputstring; 
    boost::smatch m; 
    if(boost::regex_search(inputstring, m, is_number_regex)) 
    { 
     radius = boost::lexical_cast<double>(inputstring); 
     std::cout <<"Found value for radius: "<< radius << std::endl; 
    } 
    else 
    { 
     std::cerr << "Error" << std::endl; 
    } 
} 

適應的正則表達式,如果你需要負數,科學的數字,...