为什么函数不能接受用户输入?

问题描述 投票:1回答:1
void patient_data(){    

    char name[10];
    int ID[4];
    int age;
    char history[100];
    float temp;
    int breath; 

    printf("enter patient data:\n");    

    scanf("name : %s\n", name);
    scanf("ID: %d\n",ID);
    scanf("age %d\n",&age);
    scanf("history: %s\n", history);
    scanf("temp: %f\n",&temp);
    scanf("breath: %s\n", breath);

    FILE *info;
    info = fopen("info.txt","a");   

    fscanf(info,"%s     %d  %d  %s  %f  %d",name, ID, &age, history, &temp,&breath);
}

此代码应该接受用户输入的患者数据,并将其保存在以后应访问的文件中,但scanf功能不起作用。

关于这里可能有什么问题的任何想法?

c
1个回答
0
投票

您的scanf'格式不正确,应该简单地为:

scanf(" %9s", name); //<-- added buffer limit
scanf("%d",ID);
scanf("%d",&age);
scanf(" %99s", history); //<-- added buffer limit
scanf("%f",&temp);
scanf("%d", &breath);` // <-- corrected the specifier

如果要让用户知道要输入的内容的标签,请在每个printf之前使用putsscanf

请注意,最后一个scanf具有说明符不匹配,它采用整数,但使用字符串说明符。

也请注意,"%s"说明符是不安全的,对于100个字符的容器,应使用"%99s",以避免缓冲区溢出。您拥有它的方式,并不比gets()好。

最后,写入文件的正确功能是fprintf

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