2015-05-23 22 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

相关问题