我正在尝试使用两个 scanf 来读取一个字符串,然后再读取一个整数。该程序等待我输入字符串,我按回车键,然后不等待我插入整数。我正在使用的代码:
printf("Insert the name of the author to search: ");
scanf("%300s", author);
printf("Insert the year: ");
scanf("%d", &year);
有什么建议吗?
最佳答案
转换说明符 "%s"
在空格处中断。
例如,如果您输入“John Smith”,变量 author
将具有 “John”
,其余输入将用于 年
。
始终验证(大多数)库函数的返回值。
printf("Insert the name of the author to search: ");
if (scanf("%300s", author) != 1) /* error */;
printf("Insert the year: ");
if (scanf("%d", &year) != 1) /* error */;
获取用户输入的最佳方法是使用 fgets()
,然后,如果需要,解析输入并分配给变量。
char tmp[1000];
printf("Insert the name of the author to search: ");
if (!fgets(tmp, sizeof tmp, stdin)) /* error */;
strcpy(author, tmp);
printf("Insert the year: ");
if (!fgets(tmp, sizeof tmp, stdin)) /* error */;
if (sscanf(tmp, "%d", &year) != 1) /* error */;
关于c - 使用 scanf 读取字符串然后读取整数,只读取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23325406/