繁体   English   中英

以下c程序的意外输出

[英]unexpected output of the following c program

下面的代码按预期应接受来自用户的两个char值。 但是它只接受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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM