gpt4 book ai didi

c++ - scanf() 奇怪的行为!

转载 作者:可可西里 更新时间:2023-11-01 16:36:34 26 4
gpt4 key购买 nike

我最近偶然发现了一个奇怪的案例(至少对我来说是这样,因为我以前没有遇到过)..考虑下面的简单代码:-

int x;
scanf("%d",&x);
printf("%d",x);

上面的代码接受一个普通的整数输入并按预期显示结果..

现在,如果我将上面的代码修改为:-

int x;
scanf("%d ",&x);//notice the extra space after %d
printf("%d",x);

在给出 printf 语句的结果之前,它接受了另一个额外的输入。我不明白为什么空格会导致 scanf() 的行为发生变化。任何人都可以向我解释一下....

最佳答案

来自 http://beej.us/guide/bgc/output/html/multipage/scanf.html :

The scanf() family of functions reads data from the console or from a FILE stream, parses it, and stores the results away in variables you provide in the argument list.

The format string is very similar to that in printf() in that you can tell it to read a "%d", for instance for an int. But it also has additional capabilities, most notably that it can eat up other characters in the input that you specify in the format string.

发生的事情是 scanf 是模式匹配格式字符串(有点像正则表达式)。 scanf 不断消耗来自标准输入(例如控制台)的文本,直到匹配整个模式。

在您的第二个示例中,scanf 读取一个数字并将其存储在 x 中。但它还没有到达格式字符串的末尾——还剩下一个空格字符。因此 scanf 从标准输入中读取额外的空白字符,以便(尝试)匹配它。

关于c++ - scanf() 奇怪的行为!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6349837/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com