簡體   English   中英

我在打印我的結構時遇到問題(從文件中讀取姓名和電話號碼)。 我如何解決它?

[英]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;

其次,您實際上讀取文件提供字符串的數據格式整數。 scanfprintf中使用%s而不是%d

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM