0

尝试从文件扫描到 C 数组,但出现错误。当我使用每行只有数字的文件时,它对我有用,例如:

1.2  
3.4  
5.2  

但现在我有这个文件:

0001:Satriani:Joe:6:38.0
0002:Vai:Steve:1:44.5
0003:Morse:Steve:10:50.0
0004:Van Halen:Eddie:3:25.75
0005:Petrucci:John:8:42.25
0006:Beck:Jeff:3:62.0  

这是我尝试将其扫描到数组中的方法,但出现分段错误!

FILE *employeesTXT;
int empID[100];
char lastName[100];
char firstName[100];
int payGroup[100];
double hoursWorked[100];

employeesTXT = fopen("employees.txt", "r");
if (employeesTXT == NULL)
{
    printf("Error: file cannot be opened.\n");
} else {
    while (fscanf(employeesTXT, "%[^:]:%[^:]:%[^:]:%d:%lf\n", &empID[i], lastName[i], firstName[i], &payGroup[i], &hoursWorked[i]) != EOF)
    {
        i++;
    }

    fclose(employeesTXT);
    numRecords = i;

    for(i = 0; i < numRecords; i++){
        printf("%d - %s - %s - %d - %.2lf\n", empID[i], lastName[i], firstName[i], payGroup[i], hoursWorked[i]);
    }
}  

它必须是这一行的东西...... %[^:]:%[^:]:%[^:]:%d:%lf\n

4

4 回答 4

1

您的参数参数对于字符串是错误的:

fscanf(employeesTXT, "%[^:]:%[^:]:%[^:]:%d:%lf\n",
    &empID[i], lastName[i], firstName[i], &payGroup[i], &hoursWorked[i])

lastNamefirstName声明为 100 的数组char。您希望这些是字符串,因此您需要将它们定义为 100 个“缓冲区”的数组。

尝试将声明更改为:

char lastName[100][50]; /* 50 or whatever the max length you'd expect + 1 */
char firstName[100][50];

我相信应该像那样工作。

您还有一个不同的问题empID,您将值作为字符串而不是整数读取。%d在格式中,如果这些确实是您输入中的整数,则应该是整数。

于 2012-04-11T17:17:26.537 回答
0

改变

char lastName[100];
char firstName[100];

char lastName[100][100];
char firstName[100][100];

阅读时empID[i]也不要使用%[^:]%d而是使用。

于 2012-04-11T17:22:24.157 回答
0

As pointed out, for the names you are assigning each new employees' information into an one dimensional array, thereby overwriting the previous employee's information (except the first character). This eventually leads to your error when you try to assign a long enough name to an index near the end of your array which causing it to write over the last index. You can use a two dimensional array as suggested for the names:

char lastname[number_of_employees][maximum_length_of_name];

and each lastname[i] will be a null terminated string.

But, this is what structures are made for.

// Define it before main()
struct employee_type{
    int empID;
    char *lastname;
    char *firstname;
    int paygroup;
    double hoursworked;
}

// In main()
struct employee_type employees[100]; // Declare an array of employee_type structures.
于 2012-04-11T17:54:16.073 回答
-1

您需要将地址作为参数fscanf,这不能作为参数,因为它只是一个字符:

   lastName[i]
于 2012-04-11T17:17:37.160 回答