这有点总是错的

时间:2016-09-04 21:09:10

标签: c

#include <stdio.h> 

struct Bank {
    char name[500];
    int mobile;
    float balance;
};

int main() {
    int i;
    struct Bank a[100];

    for (i = 0; i < 3; i++) {
        printf("Enter the name of person %d: ", i + 1);
        gets(a[i].name);
        printf("Enter the mobile of person %d: ", i + 1);
        scanf("%d", &a[i].mobile);
        printf("Enter the mobile of person %d: ", i + 1);
        scanf("%f", &a[i].balance);
    }

    for (i = 0; i < 3; i++) {
        puts(a[i].name);
        printf("His Balance is: %f", a[i].balance);
        printf("His Mobile number is : %d \n\n", a[i].mobile);
    }

    return 0;
}

尝试运行此用户输入请求不会像我想要的那样,只需运行它就可以理解。我做错了什么?

1 个答案:

答案 0 :(得分:2)

它没有按预期工作的原因是因为在第二次和第三次迭代时输入缓冲区上有一个换行符字符为gets(),大概来自之前的&#34;输入&#34;击中。

如果您将gets()调用更改为scanf("%s", a[i].name),它会按预期工作(如下所示)。

请注意:

  • 此代码非常容易受到多行缓冲区溢出的影响(所有scanf()和gets()调用) - 请参阅hereherehere等等,底线:你根本不应该使用gets(),也不应该使用没有边界的scanf()

  • 你在第三个printf中输了一个错字,并再次询问手机号码

相关问题