2015-05-23 21 views
0

我有這樣的代碼,這給用戶的建議,選擇在我的菜單中的選項之一:C++的getchar不工作,因爲它應該

char c; 
    do { 
     switch(c=getchar()){ 
       case '1': 
         cout << "Print" << endl; 
         break; 
       case '2': 
         cout << "Search" << endl; 
         break; 
       case '3': 
         cout << "Goodbye!" << endl; 
         break; 
       default: 
        cout << "I have this symbol now: " << c << endl; 
         break; 
       } 
     } while (c != '3'); 

因此,它想閱讀的特點,並提出我們在一個三種選擇。它確實如此。但是,只有當我按回車,和好,我可以忍受,但它也接受這些字符串作爲有效的選項:

  • dfds2kflds,fdsf3,fds1lkfd

什麼是地獄? 我希望它接受這樣才字符:

  • 1,2,3 我怎樣才能解決這個問題?我是C++的noob。
+0

Windows還是Linux?你想單字符輸入還是整行輸入? – cup

+0

Linux。我不在乎,只要它按預期工作,並不是很難。最好是單個字符,更可取的是甚至沒有按下輸入,但我認爲Inow我只是爲了解決它而去任何事情:D – Ophelia

+0

再一次,誰在我的帖子上寫了一個減號?我看不出爲什麼,只是留下評論! – Ophelia

回答

1

使用getche()getch()。如果sometthing這樣

c=getch(); 
switch(c=getch()){ 
      case '1': 
        cout<<c; 
        cout << "Print" << endl; 
        break; 
      case '2': 
        cout<<c; 
        cout << "Search" << endl; 
        break; 
      case '3': 
        cout<<c; 
        cout << "Goodbye!" << endl; 
        break; 
      default: 
        break; 
      } 

,你不會看到任何其他字符,除了1,2和3的屏幕上

**編輯**
如果CONIO.H不可用,你可以試試這個:(以行的字符丟棄休息)

char c; 
do { 
    switch(c=getchar()){ 
      case '1': 
        cout << "Print" << endl; 
        break; 
      case '2': 
        cout << "Search" << endl; 
        break; 
      case '3': 
        cout << "Goodbye!" << endl; 
        break; 
      default: 
       cout << "I have this symbol now: " << c << endl; 
        break; 
      } 
      while((c=getchar())!='\n'); //ignore rest of the line 
    } while (c != '3'); 

或丟棄,其中超過1個字符是有

輸入
char c; 
do { 
    c=getchar(); 
    if(getchar()!='\n'){ //check if next character is newline 
     while(getchar()!='\n'); //if not discard rest of the line 
     cout<<"error"<<endl; 
     c=0; // for case in which the first character in input is 3 like 3dfdf the loop will end unless you change c to something else like 0 
     continue; 
    } 
     switch(c){ 
      case '1': 
        cout << "Print" << endl; 
        break; 
      case '2': 
        cout << "Search" << endl; 
        break; 
      case '3': 
        cout << "Goodbye!" << endl; 
        break; 
      default: 
       cout << "I have this symbol now: " << c << endl; 
        break; 
      } 
    } while (c != '3'); 
+0

哦,它是一些微軟庫的一部分,不是嗎?我使用gcc編譯器,所以它不是和選項 – Ophelia

+0

包括'#include '爲getch() –

+0

那麼,它不是一個標準庫?我需要在某處下載它?我的gcc無法識別它 – Ophelia

相關問題