2014-06-10 126 views
0

我已經寫了下面的代碼,很大程度上它做我想做的事情。問題是,當用戶可以輸入類似「111」的東西,輸出是「您輸入了數字1」。我想限制用戶的輸入爲1個字符。有什麼建議麼?我確信解決方案非常簡單,但我無法弄清楚。此外,代碼必須以switch語句的形式保留。謝謝!限制用戶輸入

#include <iostream> 
using namespace std; 

int main() 
{ 
    char i; 

    cout << "Please enter a number between 1 and 9." << endl; 
    cout << "Enter a number: "; 
    cin >> i; 

    switch (i) 
     { 
     case '1': 
      cout << "You entered the number one." << endl; 
      break; 

     case '2': 
      cout << "You entered the number two." << endl; 
      break; 

     case '3': 
      cout << "You entered the number three." << endl; 
      break; 

     case '4': 
      cout << "You entered the number four." << endl; 
      break; 

     case '5': 
      cout << "You entered the number five." << endl; 
      break; 

     case '6': 
      cout << "You entered the number six." << endl; 
      break; 

     case '7': 
      cout << "You entered the number seven." << endl; 
      break; 

     case '8': 
      cout << "You entered the number eight." << endl; 
      break; 

     case '9': 
      cout << "You entered the number nine." << endl; 
      break; 

     default: 
      cout << "You did not enter a valid number." << endl; 
      break; 
     } 

    system("pause"); 
    return 0; 
} 
+1

您已將輸入限制爲一個字符。沒有辦法阻止他們在標準C++中再打字。 – chris

+0

你的輸入形式是什麼? – durbnpoisn

+0

在控制檯中,用戶可以鍵入任意數量或字符。例如。如果用戶鍵入a,則輸出將爲「您沒有輸入有效的號碼。」另一個例子是,如果用戶鍵入19,那麼程序將輸出「您輸入了數字1」。數字1是用戶輸入的第一個字符。問題是我希望程序拒絕任何不在1到9之間的數字。我有道理嗎? – user3727648

回答

0

有一種方式,這將是非常簡單:只需切換到char cint n更換case '1'case 1等試試這個,直到用戶輸入有效的號碼,然後輸入「A」(即東西是不是數字)。往往,簡單的方法也是錯誤的方式。 ;)

現在,你可以做的反而是利用這段代碼:

std::string line; 
while (getline(std::cin, line)) 
{ 
    if (line == "1") { 
     std::cout << "You entered the number one." << std::endl; 
    } else if (line == "2") { 
     // .... 
    } else { 
     std::cout << "You didn't enter a valid number" << std::endl; 
    }   
} 

這裏的區別在於,由於輸入線路基沒有進一步解釋,streamstate沒有被修改當輸入不能被解釋爲一個數字時。與用戶交互時,這通常更健壯。如果稍後想用數字表示數字,請檢查字符串流或lexical_cast以進行轉換。

+0

我重新編寫了代碼,並且您的第一個建議可行。爲什麼使用int vice可以更好地工作?我試圖理解,不僅僅是得到正確的答案。謝謝。 – user3727648

+0

@ user3727648它的工作原理是因爲在switch語句中,您將「i」與字符進行比較,而不是整數。你是否改變了'情況'1':','情況'2':'等到情況1:','情況2:'等等?如果你不這樣做會是原因。 – 0x499602D2

+0

是的,我改變了字符我int n和所有的情況下'1':情況1:等。代碼的工作方式,我想它現在。謝謝。 – user3727648

0

您可以使用getch()從屏幕獲取單個字符,您可以檢查它是否是數字,否則再次詢問是否有效輸入。

+0

這是非常不可移植的和oldschool(說在DOS時間附近)... :-) – andreee

1

您可以使用c標準io庫中的getchar(char)。

#include <stdio.h> 
    ... 
    char i; 
    int j; 

    cout << "Please enter a number between 1 and 9." << endl; 
    cout << "Enter a number: "; 
    getchar(j); 
    i=(char)j; 
    switch(i){ 
    ... 
+0

OP已經閱讀單個字符。這提供了什麼優勢? – chris