简体   繁体   English

以下c程序的意外输出

[英]unexpected output of the following c program

the following code as expected should accept two char values from user. 下面的代码按预期应接受来自用户的两个char值。 but it just accepts one value of ch1 and then prints "hello". 但是它只接受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;
}

it is not accepting the second value for ch2..what can be the possible reason? 它不接受ch2的第二个值。可能是什么原因? As far as i think, it should accept 2 characters. 据我认为,它应该接受2个字符。

It just accepts only one char because the the first call to scanf() left a newline in the input stream. 它仅接受一个字符,因为对scanf()的第一次调用在输入流中留下了换行符。

You can ignore it with: 您可以使用以下方法忽略它:

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

This will ensure the newline from the previous input will be ignored. 这将确保来自先前输入的换行符将被忽略。 A white-space in the format string tells scanf() to ignore any number of white-space characters. 格式字符串中的空格告诉scanf()忽略任意数量的空格字符。 You might also want to check the return value of scanf() calls in case it failed. 您可能还需要检查scanf()调用的返回值,以防失败。

From 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