Here https://stackoverflow.com/questions/217074/parsing-input-with-scanf-in-c,我在接受的答案中看到了这样的说法:
大多数转换说明符会跳过前导空格,包括换行符,但是%c
才不是。
对我来说,不清楚这种不同行为的基本原理,我希望有一个统一的行为(例如总是跳过或从不)。
我遇到了这样的问题,有一段 C 代码,如下所示:
#include "stdio.h"
int main(void){
char ch;
int actualNum;
printf("Insert a number: ");
scanf("%d", &actualNum);
// getchar();
printf("Insert a character: ");
scanf("%c", &ch);
return 0;
}
两者互换scanf
s 解决了问题,以及(评论的)getchar
,否则'\n'
第一个插入的值将被第二个插入消耗scanf
with %c
。我在 Linux 和 Windows 上的 gcc 上进行了测试,行为是相同的:
海湾合作委员会(GCC)4.7.2 20120921(红帽4.7.2-2)
版权所有 (C) 2012 自由软件基金会, Inc.
这是免费软件;请参阅复制条件的来源。没有
保修单;甚至不是为了适销性或特定用途的适用性。
所以我的问题是:为什么%d
and %c
表现不同w.r.t.'\n'
in scanf
?
这是一贯的行为,你只是想错了。 ;)
scanf("%c", some_char); // reads a character from the key board.
scanf("%d", some_int); // reads an integer from the key board.
所以如果我这样做:
printf("Insert a character: ");
scanf("%c", &ch); // if I enter 'f'. Really I entered 'f' + '\n'
// scanf read the first char and left the '\n'
printf("Insert a number: ");
scanf("%d", &actualNum); // Now scan if is looking for an int, it sees the '\n'
// still, but that's not an int so it waits for the
// the next input from stdin
在这种情况下,并不是它自己消耗换行符。试试这个:
char ch;
char ch2;
printf("Insert a character: ");
scanf("%c", &ch);
printf("Insert another character: ");
scanf("%c", &ch2);
它将“跳过”第二个scanf()
因为它读入'\n'
当时。scanf()
是一致的,你必须消费它'\n'
如果你要正确使用它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)