Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/eclipse/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 将文本文件读入结构并将其拆分_C_Eclipse - Fatal编程技术网

C 将文本文件读入结构并将其拆分

C 将文本文件读入结构并将其拆分,c,eclipse,C,Eclipse,调用fscanf函数时,我的程序挂起。我不知道为什么。我正在尝试从以下文本文件读取信息: R1 N001 N003 20 R2 N002 N001 5 R3 N001 0 10 R4 N002 N003 10 R5 N003 N000 5 I1 0 N002 10 这是我的结构: #include<stdlib.h> #include<stdio.h> #ifndef MYDATA_H_

调用fscanf函数时,我的程序挂起。我不知道为什么。我正在尝试从以下文本文件读取信息:

     R1 N001 N003 20
     R2 N002 N001 5
     R3 N001 0 10
     R4 N002 N003 10
     R5 N003 N000 5
     I1 0 N002 10
这是我的结构:

    #include<stdlib.h>
    #include<stdio.h>
    #ifndef MYDATA_H_
    #define MYDATA_H_

    typedef struct comp{
       char *name;
       char *node1;
       char *node2;
       float val;
    } ComponentType;

    typedef struct ListNodeT{
       ComponentType Component;
       float currnet;
       float voltage;
       float power;
    } ListNodeType;

    #endif

您的代码中有许多错误

让我们从调用
fscanf
开始:您只有读取单个字符的格式
%c”
,但是您有许多要解析的值。每个变量需要一个格式代码,并且格式代码必须正确(即字符串的
“%s”
):

注意前导空格,它告诉
fscanf
跳过输入中的前导空格,这是必需的,因为换行符仍将位于前一行的输入缓冲区中

然后让我们继续讨论可能导致上述代码崩溃的原因:您必须为字符串分配内存!动态分配(例如
CircuitData[index].name=malloc(某些大小)
)或将它们声明为数组(例如
charname[某些大小]

当您使用
node1
node2
字段时,这些字段实际上应该是整数字段(例如
int node1
)。然后,对于使用
fscanf
读取的字符串,您需要几个临时变量。标准库中有一些函数可以将字符串转换为整数,如:

你的阅读循环也有问题,你应该这样做

while (fscanf(...) == 4) { ... }
当然,我假设您已经为
CircuitData
数组分配了内存


您现在确实有很多其他与指针相关的错误,但是如果您将
node1
node2
更改为整数,其中一些错误将得到解决。

您是否初始化了CircuitData数组?
fscanf(myFile, " %s %s %s %f",
    CircuitData[index].name,
    CircuitData[index].node1,
    CircuitData[index].node2,
    &CircuitData[index].val);
CircuitData[index].node1 = strtol(temp_node1, NULL, 10);
while (fscanf(...) == 4) { ... }