c - 如何将 "%99s "克隆到 : fscanf(file, "%d %99s", &id, name) == 2)

标签 c

test.c 扫描 file.txt 并打印给定 ID 的名称。
我想向 file.txt 添加第三列

我还想问:

%99s== 2 的含义是什么: while (fscanf(fff, "%d %99s", &id, name) == 2) {

file.txt(添加新列)

1 name1 newcolumn1
2 name2 newcolumn2
3 name3 newcolumn3

修改 test.c 以使用第三列(添加 char name2[100];并克隆 %99s)

结果:不工作。 (编译:​​好的。但输出为空(什么也没有))

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

main() {
    char name[100];
    char name2[100];

    FILE *fff;

    int found = 0;
    int id;

    fff = fopen("/file.txt", "r");

    while (fscanf(fff, "%d %99s %99s", &id, name, name2) == 2) {
        if (id == 2) {
            printf("%s\n", name2);
            found = 1;
            break;
        }
    }

    fclose(fff);
    return 0;
}

最佳答案

%99s 表示程序只能接受 name 和 name2 中最多 99 个字符

现在 fscanf 返回一个 int 值,表示接受的输入数量并放入变量中。因此 fscanf(fff, "%d %99s %99s", &id, name) == 2 总是错误的,因为接受了 3 个输入。

fscanf 条件只是一个需要小心的安全措施(常见的 c 习惯用法)。

现在正确的程序是:

#include <stdio.h>

int main(void)
{
    char name[100];
    char name2[100];
    FILE *fff;
    int found = 0;
    int id;

    fff = fopen("/file.txt", "r");

    if (fff == NULL)
        return -1;

    while ( fscanf(fff, "%d %99s %99s ", &id, name, name2) == 3 )
    {
        if (id == 2)
        {
            printf("%s\n", name2);
            found = 1;
            break;
        }
    }

    fclose(fff);

    return 0;
}

关于c - 如何将 "%99s "克隆到 : fscanf(file, "%d %99s", &id, name) == 2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44670035/

相关文章:

c - 系统函数调用时出现段错误

c - 如何将从函数获得的值分配给 c 中的整数?

c - 修复用于解决搜索范围的代码

c - 编译器对 setjmp/longjmp 的特殊处理

c - 识别传递关系

c - 我不会写这个阶乘代码

c - 如何分别计算所有行的平均值

c - 在C代码中,自由功能无法将内存清除掉

c - 用C语言开发的程序可以知道是哪个操作系统编译的吗?

c - 最优数组推送