在C中使用fscanf进行输入[重复]

问题描述 投票:0回答:1
我正在尝试用c编写一个程序,该程序将一个献血者列表作为输入并将其存储在指针变量

donor

这里是包含5个个体(姓名,性别,年龄和血统)的数据的列表的示例:

Ranganath M 22 A-沙池F 27 B +拉克希米F 40 O-Sriram M 19 B +Sanandan M 35 AB +(

注意之间的空格]

这里是C代码的一部分,它从名为

donorslist.txt

的文件中获取输入。struct Bloodbank { char name[20]; char gender; int age; char bloodgrp[3]; } receiver; int main (int argc, char *argv[]) // taking input from the command line { if(argc!=5) exit(1); int found =0; strcpy(receiver.name,argv[1]); receiver.gender=*argv[2]; receiver.age = atoi(*argv[3]); strcpy(receiver.bloodgrp,argv[4]); struct Bloodbank *donor = (struct Bloodbank *)malloc(SIZE*sizeof(struct Bloodbank)); FILE *fp; fp = fopen("donorslist.txt", "r"); for(int i=0;i<SIZE;i++) // SIZE has been defined =5 { fscanf(fp,"%s[^ ]",donor[i].name); fgetc(fp); // to skip the whitespace fscanf(fp,"%c" ,&donor[i].gender); fgetc(fp); fscanf(fp,"%d" ,&donor[i].age); fgetc(fp); fscanf(fp,"%s[^\n]",donor[i].bloodgrp); fgetc(fp); //to skip the newline }
在这里,我从命令行给出的输入为:./a.out John M 30 B+

并且抛出

分段错误(核心已转储)

似乎我使用和声明结构指针的方式存在一些错误,但是我似乎无法弄清楚该怎么做。我想知道分配给结构指针的内存与诸如

int *

的通用指针以及代码中的错误有何不同。
谢谢

[我正在尝试用c编写一个程序,该程序将供血者列表作为输入并将其存储在指针变量供体中,这是一个包含5个人(姓名,性别,...)数据的列表的示例。 >

c debugging file-io structure
1个回答
1
投票
  1. 当为c字符串保留内存时,必须考虑

    null终止符

© www.soinside.com 2019 - 2024. All rights reserved.