【问题标题】:Why can't my function take the user input? [closed]为什么我的函数不能接受用户输入? [关闭]
【发布时间】:2020-09-26 20:47:24
【问题描述】:
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 函数不起作用。

对这里可能出现的问题有什么想法吗?

【问题讨论】:

  • ...不工作请详细说明。
  • 这会从文件中读取数据,而不是从用户输入中读取。如果您想获取用户输入,然后将其保存到文件中,您可以从用户处scanf 输入,然后将 fprintf 输入到文件中。
  • 您打开info 进行写入,然后使用读取功能(fscanf)

标签: c io scanf


【解决方案1】:

您的scanf's 格式不正确,它们应该是:

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

如果您想打印标签让用户知道输入什么,请在每个 scanf 之前使用 printf 或 puts。

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

还要注意"%s" 说明符是不安全的,您应该将"%99s" 用于100 字符的容器以避免缓冲区溢出。你拥有它的方式,it's no better than gets()。

最后写入文件的正确函数是fprintf。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多