2011-10-12 66 views
0

我正在製作一個函數,它從用戶的輸入中獲取一個數字並找到它的絕對值。如果用戶輸入的不只是一個數字,我想讓它返回一個錯誤。我會怎麼做呢?輸入不是數字時輸出錯誤。 C++

(我知道這可能是很多的,你一個簡單的問題,但我以我的第一個編程類C++,所以我知道的很少。任何幫助,將不勝感激。)

+0

並不多。就像我說的那樣,我對此很新,並且不知道如何去做這件事。 – gamerman1

回答

0

將用戶輸入視爲std::stringchar *,然後驗證它是否包含有效的數字字符。

0

你有沒有簽出atoi,或更好的strtol?我建議從那裏開始。

0

傳遞您的號碼作爲參考並返回錯誤代碼。使用函數參數作爲輸出參數。

bool parseNumber(int &n) 
{ 
... 
//assign to number to n 
// if number parsing is ok return true; 
... 
    return false; 
} 

int main() 
{ 
    int number=0; 

    if(!parseNumber(number)) 
     std::cout << "Number parsing failed\n"; 
} 
3

如果你真的想用慣用的C++編程,忽略你給出的(故意的?)不好的建議。尤其是指向C函數的答案。 C++在很大程度上可以向後兼容C,但它的靈魂是完全不同的語言。

你的問題是如此基礎,以使一個可怕的家庭作業。特別是如果你太過漂亮,你不知道要避免conio.h和其他悲劇。所以我只想在這裏寫出一個解決方案:

#include <iostream> 
#include <string> 

// Your function is presumably something like this 
// although maybe you are just using integers instead of floats 
float myAbs(const float x) { 
    if (x >= 0) { 
     return x; 
    } else { 
     return -x; 
    } 
} 

int main(int argc, char* argv[]) { 
    // give a greeting message followed by a newline 
    std::cout << "Enter values to get |value|, or type 'quit'" << std::endl; 

    // loop forever until the code hits a BREAK 
    while (true) { 
     // attempt to get the float value from the standard input 
     float value; 
     std::cin >> value; 

     // check to see if the input stream read the input as a number 
     if (std::cin.good()) { 

      // All is well, output it 
      std::cout << "Absolute value is " << myAbs(value) << std::endl; 

     } else { 

      // the input couldn't successfully be turned into a number, so the 
      // characters that were in the buffer that couldn't convert are 
      // still sitting there unprocessed. We can read them as a string 
      // and look for the "quit" 

      // clear the error status of the standard input so we can read 
      std::cin.clear(); 

      std::string str; 
      std::cin >> str; 

      // Break out of the loop if we see the string 'quit' 
      if (str == "quit") { 
       break; 
      } 

      // some other non-number string. give error followed by newline 
      std::cout << "Invalid input (type 'quit' to exit)" << std::endl; 
     } 
    } 

    return 0; 
} 

這讓你可以使用iostream類的自然能力。他們可以注意到,他們無法自動將用戶輸入的內容轉換爲您想要的格式,並且讓您有機會只是出現錯誤 - 或嘗試以不同方式解釋未處理的輸入。

0

這裏除了偉大的答案,你可以嘗試使用的std :: stringstream的:

http://cplusplus.com/reference/iostream/stringstream/stringstream/

它像任何其他流的大部分,所以你可以這樣做:

int converted; 
    string user_input; 

    cin >> user_input; 

    stringstream converter(user_input); 


    if(!(converter >> converted)) { 
    cout << "there was a problem converting the input." << endl; 
    } 
    else { 
    cout << "input successfully converted: " << converted << endl; 
    } 

HTH!

P.S.個人而言,我只會使用boost :: lexical_cast <>,但對於作業分配而言,您可能無法獲得提升。如果你成爲一名專業的C++程序員,Boost將成爲STL之外你最好的朋友之一。