简体   繁体   English

当我使用“scanf”时到底发生了什么?

[英]What exactly happens when I use "scanf"?

I'm trying to understand what happens when I'm using the "scanf" function, or to be more specific, what happen when I'm trying to enter letter into int with "scanf".我试图了解当我使用“scanf”function 时会发生什么,或者更具体地说,当我尝试使用“scanf”将字母输入 int 时会发生什么。

So I understood that when I'm trying to input letter into int, it's just doesn't work, so i wrote this to check what happends:所以我明白当我试图将字母输入 int 时,它根本不起作用,所以我写了这个来检查发生了什么:

#include <stdio.h>

int main()
{
    int num=0;
    char term='a';
    scanf("%d%c", &num, &term);
    printf("%d%c", num, term);
 
    return 0;
}
 

When my input is "b" for example, the output is "0a", while I excepted it to be "0b" becouse the "scanf" would not entered "b" into num, and then he would entered it into "term".例如,当我输入“b”时,output 是“0a”,而我将它排除为“0b”,因为“scanf”不会将“b”输入到 num 中,然后他将其输入到“term”中.

Does someone know why its happens?有人知道为什么会这样吗? I looked for answer and saw that its connect with the buffer but still I didn't understand what's happened.我寻找答案并看到它与缓冲区相连,但我仍然不明白发生了什么。

If you input a non-digit character when a digit is expected (like for the %d format) then scanf will fail immediately .如果在需要数字时输入非数字字符(如%d格式),则scanf立即失败。

Similarly for other formats and mismatching inputs, as soon as invalid input is detected the function will fail and return.与其他格式和不匹配的输入类似,一旦检测到无效输入,function 就会失败并返回。

You should always check what scanf returns .您应该始终检查scanf返回的内容。

When scanf fails, it will leave the input in the buffer.scanf失败时,它将输入留在缓冲区中。 So next time you read you will get that data.因此,下次您阅读时将获得该数据。

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

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