fgets() 无法正常工作

fgets() not working properly

我正在编写一个简单的代码,我需要输入一个数字 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 是不合适的,因为它会消耗所有白色 space 字符并继续请求输入,直到非 space 输入中的字符。

一种快速而肮脏的方法是将 scanf 替换为:

scanf("%d%*c", &num_msg);

%*c读取单个字符,不存储。

您也可以将它存储到一个 char 变量中并验证它确实是一个 '\n'.

一种忽略所有字符直到并包括换行符的通用方法:

scanf("%d", &num_msg);
int c;
while ((c = getchar()) != EOF && c != '\n')
    continue;

您还应该检查 scanf 的 return 值以验证数字是否已正确转换。