【问题标题】:Cannot input integer after inputting float value输入浮点值后无法输入整数
【发布时间】:2021-06-14 08:59:07
【问题描述】:

我在我的 c 程序中遇到了一个奇怪的问题。从用户那里获得浮点输入(工资)后,程序结束并跳过它要求输入整数(empcode)的行。谁能告诉我为什么会这样,我该怎么办?

#include <stdio.h>
#include <string.h>

struct employee{
    int empcode;
    float salary;
    char name[30];
};

int main(){
    struct employee e1, e2, e3;

    printf("\nEnter name for e1: ");
    gets(e1.name);
    printf("\nEnter salary for e1: ");
    scanf("%f", e1.salary);
    printf("\nEnter employee code for e1: ");
    scanf("%d", e1.empcode);
    return 0;
}

【问题讨论】:

标签: c scanf pass-by-reference


【解决方案1】:

你必须写

scanf("%f", &e1.salary);
scanf("%d", &e1.empcode);

而不是

scanf("%f", e1.salary);
scanf("%d", e1.empcode);

也就是说,您需要通过指向它们的指针通过引用传递参数。

注意函数gets是不安全的,C标准不支持。而是使用函数fgets

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-26
    • 2014-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-14
    • 1970-01-01
    相关资源
    最近更新 更多