依稀记得scanf有问题,今天又遇到了这个现象。我想这是一个众所周知的问题(?)。这是一个测试scanf的简单测试代码。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
int8_t buff[1024];
int main()
{
char option;
printf("Welcome to the demo of character device driver...\n");
while (1) {
printf("***** please enter your option *****\n");
printf(" 1. Write \n");
printf(" 2. Read \n");
printf(" 3. Exit \n");
scanf("%c", &option); // line 18
printf("your option = %c\n", option);
switch(option) {
case '1' :
printf("Enter the string(with no space) :\n");
//scanf("%[\t\n]s", buff);
scanf("%s", buff); // line 24
break;
case '2' :
printf("Data = %s\n", buff);
break;
case '3' :
exit(1);
break;
default :
printf("Enter valid option. option = %c\n", option);
}
}
}
当我运行它时(我使用调试器来跟踪它),当第 18 行第二次运行时,输入第 24 行scanf("%c", &option);最后一个省略的 '\n' 字符,然后 switch 语句打印有关选项的投诉并跳到 while 循环。
我观察到,如果我更改为,问题就消失了。我应该如何理解这种现象?使用 scanf 函数时,在 %c 或 %s 之前有空格或制表符有什么影响?scanf("%s", buff);option \nscanf("%c", &option);scanf(" %c", &option);