今天我在大学里写了一个代码。我发邮件给自己,想在家里试试。它不在VS 2013上工作。幸运的是我有VS 2017并且它确实起作用了。为什么会这样?
下面是在VS 2013上失败的代码部分:

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

typedef struct{
    char name[50];
    char pos[50];
    double sel[12];
    double annpay;
}sluj;

typedef struct{
    int num;
    sluj per[100];
}firma;

firma f;

int main(){

    int i, j;

    do{
        printf("Enter number of employees\n");
        scanf("%d", &f.num);
    } while (f.num < 1 || f.num > 100);

    for (i = 0; i < f.num; i++){
        printf("Enter the name of employee:\n");
        fflush(stdin);
        fgets(f.per[i].name, 50, stdin); //it acts like this row doesnt exist
                                 //and prints the text below
        printf("Enter the position of employee:\n");
        fgets(f.per[i].pos, 50, stdin);  //basiclly the same thing as above, but on different
                                 //structure member (both are defined char)
                                 //and it works here!

        for (j = 0; j < 12; j++){
            printf("Enter salary for %d month\n", j+1);
            scanf("%lf", &f.per[i].sel[j]);
        }
    }

    for (i = 0; i < f.num; i++){
        f.per[i].annpay = 0;

        for (j = 0; j < 12; j++){
            f.per[i].annpay += f.per[i].sel[j];
        }
    }

    for (i = 0; i < f.num; i++){
        if (f.per[i].annpay > 6000){
            printf("\n%s %lf", f.per[i].name, f.per[i].annpay);
        }
    }

    return 0;
}

我认为问题不在于VS 2017,因为即使没有它也无法工作。

最佳答案

scanf()fgets()不能很好地协同工作。scanf()读取雇员数,提交的\n仍被缓冲,并将被赋给fgets()fflush()在管道上不起作用。
例如,使用linux和glibc,您会得到相同的行为

$ ltrace ./a.out  > /dev/null
puts("Enter number of employees")                             = 26
__isoc99_scanf(2
"%d", 6295680)                                 = 1
fflush(0x7f7c6811c9e0)                                        = 0
puts("Enter the name of employee:")                           = 28
fgets("\n", 50, 0x7f7c6811c9e0)                               = 0x601088
puts("Enter the position of employee:")                       = 32

没有好的方法可以将这两个函数组合在一起;例如使用fgets()将雇员数读入字符串,然后将其转换。

关于c - C代码可在Visual Studio 2013中使用,但不能在2017中使用吗,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49201940/

10-11 19:28
查看更多