V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
abucus
V2EX  ›  C

请问这段 fscanf 的代码为什么没有达到预期的效果?

  •  
  •   abucus · 2020-10-11 08:21:17 +08:00 · 2008 次点击
    这是一个创建于 1293 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我是个 C 语言初学者,查了很多网上的资料(包括 API 文档)还是没有头绪,请了解的大佬帮忙看看。题目是用 c 代码读取一个 txt 文件,这个 txt 文件里存储了图的信息,包括节点和边,内容如下

    3
    a
    b
    c
    a b
    a c
    b c
    

    第一行的数字表示这个图有多少节点。我最初始的版本读取边信息用了 while 循环

    #include<stdio.h>
    
    int main(int argc, char *argv[])
    {
    
        int n;
    
        FILE *file = fopen(argv[1], "r");
    
        fscanf(file, "%d", &n);
    
        // read node
        char *name;
        for(int i = 0; i < n; i++)
        {
            fscanf(file, "%s", name);
            printf("read node %s\n", name);
        }
    
        //read edge
        char *name1;
        char *name2;
    
        while(fscanf(file, "%s %s", name1, name2) != EOF)
        {
            printf("read edge %s %s\n", name1, name2);
        }
    }
    

    编译无错误,执行的时候发现这个 while 循环不结束,而且输出的数据也很奇怪,如下

    read node a
    read node b
    read node c
    read edge (null) ??1?I??^H??H???PTL?F
    read edge (null) ??1?I??^H??H???PTL?F
    read edge (null) ??1?I??^H??H???PTL?F
    read edge (null) ??1?I??^H??H???PTL?F
    read edge (null) ??1?I??^H??H???PTL?F
    ...
    

    请问这是为什么呢?

    PS 我尝试只保留 while 读取,并且在 txt 文件里只保存边信息,发现读取结果是下面这样

    read edge a (null)
    read edge b (null)
    read edge a (null)
    read edge c (null)
    read edge b (null)
    read edge c (null)
    

    从这里看好像是 fscanf 好像不支持 “%s %s”这样的 format,于是我又有了新问题:

    1. 为什么同样是 while 循环读取,这里和上面的结果这么不一样?
    2. 要怎么样改才能正常工作?
    3 条回复    2020-10-11 09:27:33 +08:00
    pursuer
        1
    pursuer  
       2020-10-11 08:40:19 +08:00 via Android
    看起来没有给 name 分配内存,像 char *name=(char *)malloc(50)或者 char name[50]这样?
    BrettD
        2
    BrettD  
       2020-10-11 09:10:33 +08:00 via iPhone
    name 是野指针啊!
    abucus
        3
    abucus  
    OP
       2020-10-11 09:27:33 +08:00
    @pursuer @BrettD 还真是这个问题,改了以后就正常了,多谢大佬们
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2908 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 13:59 · PVG 21:59 · LAX 06:59 · JFK 09:59
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.