首页 > 解决方案 > 我想从文本文件中读取空格分隔的数字,然后使用 struct 将其存储到数组中

问题描述

我的文本文件:

(与此处粘贴的结构相同---->以空格分隔的2位数字)

5 5
6 7
3 0
5 5
6 7
3 1
1 0
4 1
3 0
6 7
1 1
6 7
7 0

我有一个结构,我必须使用它将值存储到一个数组中,然后从那里访问存储的值。

我正在使用的源代码是:

#include <stdio.h>
#include <stdlib.h>
#define MAXPROGRAMSIZE 100
#define MAXDATASIZE 10
typedef struct Instruction{
    int opCode;
    int Address;
 } Instruction;
int main(int argc,char *argv[])
{
    FILE *fp;
    int i=0;
    Instruction IM[MAXPROGRAMSIZE];
    fp = fopen("cgs.txt", "r"); //read file *use arg[i]
    if (fp == NULL)
        printf("Cannot open file!");
    else
    {

        printf("Assembling program...\n");
        while(fscanf(fp, "%d, %d", &IM[i].opCode, &IM[i].Address) != EOF)
        {
            i++;
        }
}
//this give me junk values
printf("\nm[i].opCode is %d\n", IM[1].Address);
return 0;

}

请给我建议一个解决方案,我尝试从这里使用不同的帖子从文本文件中读取空格分隔的数字并将值存储到数组中。将不胜感激。谢谢

标签: c

解决方案


在 fscanf 中,逗号 (,) 不正确

    while(fscanf(fp, "%d, %d", &IM[i].opCode, &IM[i].Address) != EOF)

文本文件没有。


推荐阅读