c - fscanf 转结构体数组

标签 c input structure scanf

我正在尝试从文本文件中获取一些输入,将其放入结构中并将其打印出来。示例文本文件如下所示:

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 );
}

然后,您可以使用 sscanfstrtok 或许多其他方法从刚刚读取的字符串中提取数据。

我建议不要将您的电话号码存储为整数。电话号码最好用字符串表示。

关于c - fscanf 转结构体数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19847552/

相关文章:

c - 程序在C中无限运行,在编译或运行时没有错误

c - 指向固定地址的函数指针

c - 以下代码对于结构指针有何作用?

python - 大型 python tornado 项目的最佳结构是什么?

c - GET请求获取页面内容

c - 在 Windows 上使用 sys/socket.h 函数

c++ - 生成一个 keyPressEvent/Input

html - Firefox - 在 HTML 文本输入中可滚动的文本

css - IE/Edge 中复选框失败的切换布局

c++ - 在类数据结构中存储地址和路由信息