【发布时间】:2021-09-22 08:47:29
【问题描述】:
我依稀记得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 行中的 scanf("%c", &option); 第二次运行时,输入第 24 行中最后一个 scanf("%s", buff); 中遗漏的 '\n' 字符,使 @ 987654324@ \n 和 switch 语句打印有关选项的投诉并跳到 while 循环。
我观察到如果我将scanf("%c", &option); 更改为scanf(" %c", &option);,问题就消失了。我应该如何理解这种现象?使用scanf函数时,%c或%s前有空格或制表符有什么作用?
【问题讨论】:
-
@RetiredNinja 是的,这回答了我的问题。谢谢!
标签: c char scanf whitespace