错误C2143:语法错误:缺少';'在结构

时间:2015-12-15 05:25:41

标签: c struct

编译此代码时:

#include <stdio.h>
void main() {
int n, i, total=0;
printf("Enter the number of employees");
scanf("%d", &n);

struct emprecord
{
    int salary, total;
    char name[50];
};
struct emprecord emp[50];
for (i=0; i<n; i++) {
    printf("Enter the name of employee %d", i+1);
    scanf("%s", &emp[i].name);
    printf("Enter the salary of employee %d", i+1);
    scanf("%d", &emp[i].salary);
    total=total+emp[i].salary;
}
printf("Total salary is: %d", total);
}

我收到以下错误,我假设一旦解决了第一个问题,所有问题都将解决:

  

C:\ Users \ shihab130489 \ Documents \ Cpp18888r6u54ru.c(8):错误C2143:
  语法错误:缺少';'在''之前   C:\ Users \ shihab130489 \ Documents \ Cpp18888r6u54ru.c(10):错误C2143:
  语法错误:缺少';'在“类型”之前   C:\ Users \ shihab130489 \ Documents \ Cpp18888r6u54ru.c(12):错误C2133:   'emp':未知大小
  C:\ Users \ shihab130489 \ Documents \ Cpp18888r6u54ru.c(13):错误C2059:语法错误:'for'
  C:\ Users \ shihab130489 \ Documents \ Cpp18888r6u54ru.c(13):错误C2143:
  语法错误:在'&lt;'之前缺少'{'   C:\ Users \ shihab130489 \ Documents \ Cpp18888r6u54ru.c(13):错误C2059:语法错误:'&lt;'

  C:\ Users \ shihab130489 \ Documents \ Cpp18888r6u54ru.c(13):错误C2143:
  语法错误:在'++'之前缺少'{'   C:\ Users \ shihab130489 \ Documents \ Cpp18888r6u54ru.c(13):错误C2059:语法错误:'++'
  C:\ Users \ shihab130489 \ Documents \ Cpp18888r6u54ru.c(13):错误C2059:语法错误:')'
  C:\ Users \ shihab130489 \ Documents \ Cpp18888r6u54ru.c(20):错误C2143:
  语法错误:'string'之前缺少')'   C:\ Users \ shihab130489 \ Documents \ Cpp18888r6u54ru.c(20):错误C2143:
  语法错误:在'string'之前缺少'{'   C:\ Users \ shihab130489 \ Documents \ Cpp18888r6u54ru.c(20):错误C2059:语法错误:''
  C:\ Users \ shihab130489 \ Documents \ Cpp18888r6u54ru.c(20):错误C2059:语法错误:')'
  C:\ Users \ shihab130489 \ Documents \ Cpp18888r6u54ru.c(21):错误C2059:语法错误:'}'

有人可以帮忙解决第一个错误吗?我无法理解问题所在。

2 个答案:

答案 0 :(得分:1)

Microsoft C编译器(似乎VS2013之前)似乎只接受C89 / C90,并且只允许函数中任何可执行语句之前的类型和变量定义。您试图在一些可执行语句之后声明结构。这在C ++和C99和C11中都有效,但在C90中没有。

因此:

#include <stdio.h>
int main(void)
{
    int n, i, total = 0;
    struct emprecord
    {
        int salary, total;
        char name[50];
    };
    struct emprecord emp[50];
    printf("Enter the number of employees");
    if (scanf("%d", &n) != 1)
    {
        fprintf(stderr, "Did not read a number successfully\n");
        return 1;
    }
    if (n <= 0 || n > 50)
    {
        fprintf(stderr, "Error: you entered %d but it should be in the range 1..50\n", n);
        return 1;
    }

    for (i = 0; i < n; i++)
    {
        printf("Enter the name of employee %d", i+1);
        if (scanf("%s", &emp[i].name) != 1)
            break;  // Sloppy but effective
        printf("Enter the salary of employee %d", i+1);
        if (scanf("%d", &emp[i].salary) != 1)
            break;  // Sloppy but effective
        total += emp[i].salary;
    }
    printf("Total salary is: %d\n", total);
    return 0;
}

当你只对工资感兴趣时,让人们输入名字是残忍的。

答案 1 :(得分:0)

最好将struct定义放在main之前。

但是,当我使用gcc 4.5.1

时没有错误