gpt4 book ai didi

c - 以下 c 程序的意外输出

转载 作者:行者123 更新时间:2023-11-30 15:12:25 24 4
gpt4 key购买 nike

以下代码按预期应接受来自用户的两个字符值。但它只接受 ch1 的一个值,然后打印“hello”。

#include<stdio.h>

int main()
{
char ch1, ch2;

printf("Enter a char: ");
scanf("%c",&ch1);

printf("Enter second char: ");
scanf("%c",&ch2);



printf("Hello");
return 0;
}

它不接受 ch2 的第二个值..可能的原因是什么?据我认为,它应该接受 2 个字符。

最佳答案

它只接受一个字符,因为第一次调用 scanf() 在输入流中留下了换行符。

您可以通过以下方式忽略它:

scanf(" %c",&ch2); // note the leading space.

这将确保先前输入的换行符将被忽略。格式字符串中的空白告诉 scanf() 忽略任意数量的空白字符。您可能还想检查 scanf() 调用的返回值,以防失败。

来自scanf() :

    .     A sequence of white-space characters (space, tab, newline,
etc.; see isspace(3)). This directive matches any amount of
white space, including none, in the input.

关于c - 以下 c 程序的意外输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35089565/

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