输入到C控制台应用程序返回令人困惑的条件输出响应组合



编写此测试代码以尝试在较大的项目中嗅出错误。

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char newCalculation;
    printf("Enter a Y/N value for newCalculation");
    scanf("%c", &newCalculation);
    do
    {
         printf("Yes! %c", newCalculation);
    }while( tolower( newCalculation ) == 'y' );
    if( tolower( newCalculation ) == 'n' )
    {
        printf("Nope.");
    }
    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.");
        scanf("%c", &newCalculation);
    }
    return 0;
}

在命令行输入'y'应该返回

Yes! y

在命令行输入'n'应该返回

No. n

任何其他输入都应该发出一个"无效"响应和一个新的输入提示。

然而,当我输入'y'时,我得到:

Yes!  This is not a valid response.  Please enter "y" if you want to do another calculation, or enter "N" to exit.

是什么原因造成的?快把我逼疯了。

您应该使用scanf(" %c", &newCalculation);(注意%c之前的空格),尽管我会使用getchar()来获得单个字符。

同样,你的流在这里也没有意义:

 do {
     printf("Yes! %c", newCalculation);
 } while( tolower( newCalculation ) == 'y' );

E。当我在修正后的程序中输入y时,它明显会无限循环。

如果输入为'y',则程序无限输出Yes! y

,当输入为'n'时输出' Yes! nNope.

输出为Yes! xThis is not a valid response. Please enter "Y" if you want to do another calculation, or enter "N" to exit. This is not a valid response. Please enter "Y" if you want to do another calculation, or enter "N" to exit.

如果你的输入不是y || n。

你的程序完全错了,永远不会做你期望它做的事。

这是你想要的版本

 #include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
    char newCalculation;
    printf("Enter a Y/N value for newCalculation");
    scanf(" %c", &newCalculation);
    do {
      if (tolower(newCalculation) == 'y') {
      printf("Yes! %c", newCalculation);
      break;
      } else  if( tolower( newCalculation ) == 'n' ) {
       printf("Nope.");
       break;
        } else  {
      printf("This is not a valid response.n Please enter "Y" if you want to do another calculation, or enter "N" to exit.");
      scanf(" %c", &newCalculation);
    }
    } while (1);
    return 0;
}

最新更新