编译器如何理解以下C程序的给定特定输入? [英] How exactly the compiler understands the given specific input for the following C program ?

查看:83
本文介绍了编译器如何理解以下C程序的给定特定输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>
    main()
    {
    int a,b,c;
    // "a" is a two-digit integer and "b" is a five-digit integer.
    printf("Enter suitable integer values for a and b :\n");
    scanf("%2d %5d",&a,&b);
    printf("a = %2d and b = %5d\n",a,b);
    printf("Enter an integer value for c :\n");
    scanf("%d",&c);
    printf("c = %d\n",c);
    getchar();
    }





输入:

12345 32196

输出:

a = 12和b = 345

c = 32196



我理解的部分:

这里编译器为a分配12,因为a的字段宽度是2.



我不理解的部分:

为什么编译器将12345的剩余数字分配给b而将345的剩余数字分配给c?



我尝试了什么:



我试过在我的教科书中寻找解释但没有找到它。



Input :
12345 32196
Output :
a = 12 and b = 345
c = 32196

The part that i understand :
Here the compiler assigns "12" to a, since field-width of "a" is 2.

The part that i don't understand :
Why does the compiler assign the remaining digits of "12345" to "b" and that of "345" to "c" ?

What I have tried:

I have tried looking for the explaination in my textbook but didn't find it.

推荐答案

因为这就是你要求它做的事情!

当你在scanf格式字符串中指定一个长度时,它就是它所看到的: a href =http://www.cplusplus.com/reference/cstdio/scanf/> scanf - C ++参考 [ ^ ]

如果你看看白人 pace:

Because that is what you asked it to do!
When you specify a length in the scanf format string, that is what it looks at: scanf - C++ Reference[^]
And if you look under "whitespace":
Whitespace character: the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none).

不是最后一位(我制作的)它大胆所以它更清晰了)

所以你的格式字符串是:

Not the last bit (I made it bold so it's clearer)
So your format string goes:

"%2d" - OK, I need two digits... 1 and 2. Excellent!
" "   - OK, I might need some whitespace - what's the next character? A digit? that'll do!
"%5d" - OK, I need five digits... 3, 4, 5...and a space. So that's the end of that number.

所以当你以后做下一个scanf时,它仍然有缓冲区中的数据,然后进行处理。

如果你想要它的表现不同的是,您需要将数据作为字符串读取,并自行分解!

So when you later do the next scanf, it still has data in the buffer, and processes that.
If you want it to behave differently, you will need to read the data as a string, and break it up yourself!


这篇关于编译器如何理解以下C程序的给定特定输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆