我正在尝试从文本文件中获取一些输入,将其放入结构中并将其打印出来。示例文本文件如下所示:
2
Curtis
660-------
Obama
2024561111
(第一个号码上的数字被划掉了(出于隐私考虑),第二个是 Whitehouse.gov 的号码,我打电话过,他们帮不了我。)
示例输出:
204-456-1111 Obama
660--------- Curtis
(当我弄清楚其余部分时,格式和排序应该不是问题。)
我的问题用下面的问号标记(在第一个 FOR 循环中,如何从文本文件中获取特定行来创建结构?
#include <stdio.h>
#include <string.h>
struct telephone {
char name[80];
long long int number;
}
main() {
struct telephone a, b;
char text[80];
int amount, i;
FILE *fp;
fp = fopen("phone.txt", "r");
fscanf(fp, "%d", amount);
struct telephone list[amount];
for(i = 0; i < amount; i++) {
strcpy(list[i].name, ???);
list[i].number, ???);
}
fclose(fp);
for(i = 0; i < amount; i++) {
DisplayStruct(list[i]);
}
}
DisplayStruct(struct telephone input) {
printf("%lld %s\n", input.number, input.name);
}
最佳答案
使用fgets
一次读取一行。
int lnum = 0;
char line[100];
while( fgets(line, sizeof(line), fp) ) {
lnum++;
printf( "Line %d : %s\n", lnum, line );
}
然后,您可以使用 sscanf
或 strtok
或许多其他方法从刚刚读取的字符串中提取数据。
我建议不要将您的电话号码存储为整数。电话号码最好用字符串表示。
关于c - fscanf 转结构体数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19847552/