gpt4 book ai didi

C++ getchar 不能正常工作

转载 作者:行者123 更新时间:2023-11-28 06:15:35 24 4
gpt4 key购买 nike

我有这段代码,它会建议用户在我的菜单中选择一个选项:

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

因此,它假设要读取字符并将我们置于三个选项之一。确实如此。但只有在我按下 Enter 之后,好吧,我可以接受它,但它也接受这些字符串作为有效选项:

  • dfds2kflds, fdsf3, fds1lkfd

什么鬼?我希望它只接受这样的字符:

  • 1, 2, 3我该如何解决?我是 C++ 的菜鸟。

最佳答案

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

关于C++ getchar 不能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30408970/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com