我正在编写一个简单的代码,我需要输入一个数字 n,然后是格式为“string int”的 n 个字符串(例如 hello 100)。我使用 fgets()
函数来获取字符串输入。该代码似乎适用于除第一个迭代之外的所有迭代。第一次迭代似乎对 cmd 有一个空输入,但其余迭代运行良好。我尝试了各种函数,如 scanf()
和 gets()
,但问题仍然存在。谁能指出问题所在?
#include <stdio.h>
#include <stdlib.h>
int main() {
int num_msg, i;
printf("Hello, How many strings should I read?: ");
scanf("%d", &num_msg);
for (i = 0; i < num_msg; i++) {
int child;
char cmd[100], msg[100];
printf("Message %d (<msg> <int>):", i + 1);
if (fgets(cmd, sizeof(cmd), stdin)) {
//printf("cmd %s\n", cmd);
sscanf(cmd, "%s %d %*s", msg, &child); //separates string and int
printf("%s %d \n", msg, child); //prints them
}
}
}
最佳答案
需要消费scanf()
读取的数字后面的\n
。
在 scanf()
格式的末尾添加一个 \n
是不合适的,因为它会消耗所有空白字符并一直请求输入,直到一个非空格字符在输入中。
一种快速而肮脏的方法是将 scanf
替换为:
scanf("%d%*c", &num_msg);
%*c
读取单个字符并且不存储它。
您也可以将它存储到一个 char
变量中并验证它确实是一个 '\n'
。
忽略包括换行符在内的所有字符的通用方法:
scanf("%d", &num_msg);
int c;
while ((c = getchar()) != EOF && c != '\n')
continue;
您还应该检查 scanf
的返回值以验证数字是否已正确转换。
关于c - fgets() 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35806695/