首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

如何把txt文件中的数据输入到结构体数组

2012-05-16 
怎么把txt文件中的数据输入到结构体数组我有个文件的内容是1 E2 E3 W4 E5 W6 W7 W8 E9 W10 E11 E12 E13 W1

怎么把txt文件中的数据输入到结构体数组
我有个文件的内容是
1 E
2 E
3 W
4 E
5 W
6 W
7 W
8 E
9 W
10 E
11 E
12 E
13 W
14 E
15 E
但15不是确定的,长度可以从键盘上输入,我建了个结构体
struct baboon
{
int arrive_time;
int direction;
int rope_position;
};
但我想是不是应该建个结构体数组,怎么从TXT文件中把值赋给arrive_time和direction? 1 E 是一个, 2 E第2个,这样下去。给个代码看看,谢谢。

[解决办法]

C/C++ code
//我有个文件i.txt的内容是//1 E//2 E//3 W//4 E//5 W//6 W//7 W//8 E//9 W//10 E//11 E//12 E//13 W//14 E//15 E//总行数不是确定的#include <stdio.h>#define MAXN 1000struct baboon {    int arrive_time;    int direction;    int rope_position;} b[MAXN];FILE *fi;int i,n;char ln[10];char d[2];int main() {    fi=fopen("i.txt","r");    if (NULL==fi) {        fprintf(stderr,"Can not open file i.txt!\n");        return 1;    }    i=0;    while (1) {        if (NULL==fgets(ln,10,fi)) break;        if (2==sscanf(ln,"%d%1s",&b[i].arrive_time,&d)) {            switch (d[0]) {                case 'E':b[i].direction=0;break;                case 'S':b[i].direction=1;break;                case 'W':b[i].direction=2;break;                case 'N':b[i].direction=3;break;                default :                    fprintf(stderr,"Line %d Format Error:%s",i+1,ln);                break;            }            i++;            if (i>=MAXN) {                fprintf(stderr,">%d Lines Ignored!\n",MAXN);                break;            }        } else {            fprintf(stderr,"Line %d Format Error:%s",i+1,ln);        }    }    fclose(fi);    n=i;    for (i=0;i<n;i++) printf("%2d %c\n",b[i].arrive_time,"ESWN"[b[i].direction]);    return 0;}// 1 E// 2 E// 3 W// 4 E// 5 W// 6 W// 7 W// 8 E// 9 W//10 E//11 E//12 E//13 W//14 E//15 E 

热点排行