怎么把txt文件中的数据输入到结构体数组

b26232 2012-05-14 04:35:54
我有个文件的内容是
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个,这样下去。给个代码看看,谢谢。
...全文
212 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
酱油党 2012-05-15
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 的回复:]
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 1000
struct b……
[/Quote]赵哥帮人拉屎拉
b26232 2012-05-15
  • 打赏
  • 举报
回复
谢谢zhao4zhong1了,写的太好了
赵4老师 2012-05-14
  • 打赏
  • 举报
回复
//我有个文件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 1000
struct 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
酱油党 2012-05-14
  • 打赏
  • 举报
回复
这个是笨方法都能解决的问题,哥们好好想想、
如果想不到就是书没看好
W170532934 2012-05-14
  • 打赏
  • 举报
回复
定义一个字符串,然后打开文件,然后fgets,接着处理字符串,然后读完后关闭文件。
b26232 2012-05-14
  • 打赏
  • 举报
回复
能具体讲讲吗?
赵4老师 2012-05-14
  • 打赏
  • 举报
回复
fgets
sscanf

64,685

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧