c-三个输入字符的比较不正确



我有下面的程序,它比较三个字符并输出它们的比较结果。

当我运行程序时,每当我输入三个整数时,只有最后一个else(所有首字母缩写都不同(语句才能正确运行。但是,对于其他条件,只有最后一个else if(首字母和末字母缩写相同(运行。我在添加大括号后也检查了一下,但没有任何变化。

#include<stdio.h>
#include<stdlib.h>
int main()
{
char ch1, ch2, ch3;
printf("Enter 3 character values into ch1, ch2, and ch3: ");
scanf("%c%c%c", &ch1, &ch2, &ch3);
if(ch1==ch2)
{
if(ch2==ch3)
printf("All initials are the same!n");
else
printf("First two initials are the same!n");
}

else if(ch2==ch3)
{
printf("Last two initials are the same!n");
}

else if(ch1==ch3)
{
printf("First and last initials are the same!n");
}


else
{
printf("All initials are different!n");
}


system("pause");
return 0;
} 

您发布的代码运行良好,只要您在输入首字母之间不输入任何空白字符(我用AAAAABABAABBABC进行了测试,均给出了正确的响应。(

但是,如果在首字母之间输入空格(即输入A A B(,则空格字符将被读取为输入(这就是%c格式说明符的工作方式(,因此,在这种情况下,三个首字母将实际上是AA——给出的答案似乎不正确。

要跳过输入之间的(可选(空白字符,只需在每个%c格式说明符之间添加一个空格,如下所示:

scanf("%c %c %c", &ch1, &ch2, &ch3);

最新更新