【发布时间】:2013-02-26 23:04:21
【问题描述】:
我尝试将文本文件的内容加载到结构中。
我的想法是这样的:
我有两个文件,struct.h、main.c 和一个 list.txt 文件。
在文件struct.h:
struct analg {
char word[6];
char signature[6];
};
struct analg h[106];
FILE *fp;
在文件main.c:
#include<stdio.h>
#include "struct.h"
void load() {
fp = fopen("list.txt", "r");
if(fp == NULL) {
printf("fail");
return 1;
}
else {
printf("file loaded!\n");
}
fclose(fp);
return;
}
void print() {
int i;
for(i=0; i<1000; i++) {
while(fgets(h[i].word, 6, fp)) {
printf("%s", h[i].word);
}
}
return;
}
int main () {
int choice;
do {
printf("choose L or P: ");
scanf("%s", &choice);
switch(choice) {
case 'l':
load();
printf("\n[l]oad - [p]rint\n");
break;
case 'p':
print();
printf("\n[l]oad - [p]rint\n");
break;
default:
break;
}
} while(choice!='q');
return;
}
在文件list.txt:
throw
timer
tones
tower
trace
trade
tread
所以我尝试通过按“L”来加载文本文件到结构,然后当我按“p”时会显示,但它不是!
【问题讨论】:
-
scanf("%s", &choice);需要一个指向char数组的指针。此外,大小写很重要,您只测试小写字母。 -
是的,当我写 p 时没有任何效果!只有L!
-
@HaidoManeen 是的,正如 DanielFischer 所说,那是因为你的代码被破坏了。
-
坏了?我不明白?