c - 我想从文本文件中读取空格分隔的数字,然后使用 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;
}
请给我建议一个解决方案,我尝试从这里使用不同的帖子从文本文件中读取空格分隔的数字并将值存储到数组中。将不胜感激。谢谢
解决方案
在 fscanf 中,逗号 (,) 不正确
while(fscanf(fp, "%d, %d", &IM[i].opCode, &IM[i].Address) != EOF)
文本文件没有。
推荐阅读
- ruby-on-rails - Rails 6.1 参数编码设置为 ASCII-8BIT
- facebook - facebook messenger curl 请求返回
- docusignapi - Docusign 文档 URL 链接到空白模板
- php - 使用 PHP 集成 oauth 访问令牌
- reactjs - 为什么AsyncStorage在第一次单击时保存一个空数组,然后仅在第二次单击时保存输入的值?
- angular - 从 json 角度返回对象对象中获取数据
- math - 找到同时满足以下条件的 3D 向量
- events - 接收消息时是否应该手动设置用户会话?
- python - 为什么我在这个神经网络中接收 2 个值的 2 值元组上出现值错误?
- java - 加密后编码,如何在Java小程序中用AES正确解密和解码