C ++ getchar不能正常工作

时间:2015-05-23 04:47:04

标签: 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 ++的菜鸟。

1 个答案:

答案 0 :(得分:1)

使用getche()getch()。如果你做这样的事情

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');