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 ++的新手。
dev_ankit

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章