c - 使用 scanf 读取字符串然后读取整数,只读取字符串

标签 c string int scanf

我正在尝试使用两个 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/

相关文章:

C 'generics' -- double 和 float

c++ - strtok_r函数如何返回值?

iphone - 使用 OpenGL ES 2.0 显示/处理 iPhone 相机帧

c - string 和 malloc...出了什么问题?

c - 测试两个 __m128i 变量之间的相等性

c++ - 使用 string::find 和 string::substr 拆分字符串的函数返回错误的标记

string - LiveCode 查找表字段中的列表项

c# - 使用 uint 或 int

c# - 在 C# 中比较字符串和整数

Java 扫描器 nextInt(16) 不接受负十六进制值