简体   繁体   English

为什么下面的代码没有接受所有输入?

[英]why following code is not taking all inputs?

#include <stdio.h>
int main()
{
   int a;
    float b;    
    char ch;
    
        scanf("%d%f%c",&a,&b,&ch);
        printf("%d %f %c",a,b,ch);
    return 0;
}

whenever I run above code每当我运行上面的代码

its takes only two inputs and terminates why is that?它只需要两个输入并终止为什么会这样? I want to input:2,3.5,d.but its terminates after 3.5.我想输入:2,3.5,d.但它在 3.5 之后终止。

here is image of when I run the code: https://i.stack.imgur.com/ef6CE.png这是我运行代码时的图像: https://i.stack.imgur.com/ef6CE.png

Include spaces in format string.格式字符串中包含空格。 Otherwise any whitespace character (spaces, newline and tab characters) will be read into your variables.否则,任何空白字符(空格、换行符和制表符)都将被读入您的变量。 So, include a space before %c like this:因此,在%c之前包含一个空格,如下所示:

scanf("%d%f %c",&a,&b,&ch);

I think that the problem is the fact that you do not have a whitespace between the "%f" and %c" conversion specifiers, and without it after the "%f" scanf() consumes the newline character as the given character.我认为问题在于您在“%f”和 %c” 转换说明符之间没有空格,并且在“%f”scanf() 将换行符作为给定字符使用之后没有空格。

this might help you https://man7.org/linux/man-pages/man3/scanf.3.html这可能会对你有所帮助

As a matter of a fact, I placed a whitespace between the "%f" and "%c", and the following program seems to work on https://www.onlinegdb.com/online_c_compiler事实上,我在“%f”和“%c”之间放置了一个空格,下面的程序似乎可以在https 上运行://www.onlinegdb.com/online_c_compiler

#include <stdio.h>

int main()
{
    int a;
    float b;    
    char ch;

    scanf("%d%f %c",&a,&b,&ch);
    printf("%d %f %c",a,b,ch);
    return 0;
}

Furthermore, if you print your data using parenthesis 'printf("(%d %f %c)",a,b,ch);此外,如果您使用括号打印数据'printf("(%d %f %c)",a,b,ch); you will see the consuming of the newline character for yourself.您将看到自己消耗换行符。

The output of the original program, without the whitespace between %f, %c:原程序的output,%f、%c之间没有空格:

2
3.5
(2 3.500000 
)

The output of the edited program, with the whitespace between %f, %c:编辑后程序的output,%f、%c之间有空格:

2
3.5
x
(2 3.500000 x)

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

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