【发布时间】:2015-09-19 18:22:00
【问题描述】:
我正在尝试向我的 C 控制台应用程序计算器添加一项功能,提示用户决定是否要使用:y 或 n 执行另一个计算,但在测试中,getchar() 拒绝等待输入并且程序继续进行,就好像它已经收到了有效的输入一样。以下是该功能的一个最小示例:
main()
{
char newCalculation;
do{
lengthFormula(); /* main calculation formula */
printf("Would you like to do another calculation? (Y/N)");
newCalculation = getchar();
}while(tolower( newCalculation ) == 'y');
if(tolower(newCalculation) == 'n'){
exitProgram(); /* exit the program */
}
while(tolower(newCalculation) != 'n' && tolower(newCalculation) != 'y'){
printf("This is not a valid response.\n Please enter \"Y\"
if you want to do another calculation,
or enter \"N\" to exit.\n");
newCalculation = getchar();
}
return 0;
}
当我运行这个时,程序不会等待输入:
Would you like to do another calculation? (Y/N)
,而是像接收到无效输入一样继续进行。结果是一个接一个地吐出提示和无效输入通知,没有空格:
Would you like to do another calculation? (Y/N)
This is not a valid response.
Please enter \"Y\" if you want to do another calculation, or enter \"N\" to exit.
如果我在这之后输入"y",main() 返回0 并且程序终止。
有人能看到我在哪里出错了吗?
为什么控制台不等待getchar() 的输入?
为什么有效输入在第一次无效响应后终止程序?
P.S.:请不要告诉我“读一本书”或把我赶到 Dennis Ritchie 或之前关于输入的 SO 讨论之一。我一直在仔细研究 Richie 对 I/O 的讨论,以及来自 Lynda.com 和 Wiley 的类似文本,据我所知,之前的“它不会等待输入”的帖子都没有解决我的问题。
@simplicisveritatis 这是我尝试对您的代码进行的修改。仍然有相同的 getchar 问题。
int main(void)
{
/* local variable declaration */
char newCalculation = 'y';
/* main function */
/*if(tolower( newCalculation ) == 'y')
{
lengthFormula(newCalculation);
}*/
do
{
lengthFormula();
printf("Would you like to do another calculation? (Y/N)");
newCalculation = getchar();
if( tolower( newCalculation ) == 'n' )
{
exitProgram();
}
while( tolower( newCalculation ) != 'n' && tolower( newCalculation ) != 'y' )
{
printf("This is not a valid response.\n Please enter \"Y\" if you want to do another calculation, or enter \"N\" to exit.\n");
newCalculation = getchar();
}
}while( tolower( newCalculation ) == 'y' );
return 0;
}
【问题讨论】:
-
在完成@user3121023 提供的更正后,程序在重新输入错误条目后退出,因为没有循环让它重新开始。如果您正确缩进/对齐代码,这将是显而易见的。