[英]I am having problems printing my struct (with names and phone numbers read from a file). How do I fix it?
typedef struct Data
{
int name;
int surname;
int phone;
} Data;
char buf[50];
void main(int argc, char *argv[])
{
FILE *file;
file = fopen("src.txt", "r");
if (file == NULL)
{
printf("The file is empty or doesnt exist.\n");
exit(-1);
}
fgets(buf, sizeof(buf), file);
Data dat[100];
int i;
while (!feof(file))
{
Data *d = dat + i;
sscanf(buf, "%d %d %d", &dat->name, &dat->surname, &dat->phone);
fgets(buf, sizeof(buf), file);
i++;
}
int n = i;
for (i = 0; i < n; i++)
{
printf("Name: %d\nSurname: %d\nPhone: %d\n", dat[i].name, dat[i].surname,
dat[i].phone);
}
fclose(file);
exit(0);
}
我正在嘗試將文件的行讀入結構,然后打印該結構。 該文件如下所示:
Name Surname Phonenumber
Heinz Friedrich 015134532525
Amy Albertson 015443246678
當我嘗試打印結構時,它只會顯示隨機數。 我也嘗試使用字符,但它只是說“分段錯誤(核心轉儲)”
主要有兩個問題:
首先,您不初始化變量i
,這樣Data *d = dat + i
將產生未定義的行為; 使用int i = 0
而不是int i;
其次,您實際上讀取文件提供字符串的數據格式整數。 在scanf
和printf
中使用%s
而不是%d
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.