简体   繁体   English

将文件中的字符串和整数扫描到 C 中的数组中

[英]Scanning strings and ints from file into array in C

I am scanning from a file into parallel arrays.我正在从文件扫描到并行阵列。 I successfully scan the strings, but the ints and floats do not scan correctly!我成功扫描了字符串,但是整数和浮点数没有正确扫描! What is going wrong here???这里出了什么问题??? Num, human, and cool are arrays declared in the main function. Num、human 和 cool 是在 main 函数中声明的数组。

An example of a record in hello.txt: Angela, Merkel, 50, 10, 9.1 hello.txt 中的记录示例: Angela, Merkel, 50, 10, 9.1

void read(int *lines, char first[ENTRY][FIRST], char last[ENTRY][LAST], int *num, int *human, float *cool)
{
FILE *ifile;
int i;

ifile = fopen("hello.txt", "r");

fscanf(ifile, "%[^,] %*c %[^,] %*c %d %*c %d %*c %f", first[0], last[0], &num[0], &human[0], &cool[0]);

printf("%s", first[0]);
printf("%s\n", last[0]);
printf("%d\n", num[0]);
printf("%d\n", human[0]);
printf("%f", cool[0]);



fclose(ifile);
}

尝试

fscanf(ifile, "%[^,] %*c %[^,] %*c %d %*c %d %*c %f", first[0], last[0], num, human, cool);

First, with scanf family of functions, a space matches any amount of white space, including none, in the input, also don't use %*c , it is not necessary.首先,对于scanf系列函数,空格匹配输入中任意数量的空格,包括无空格,也不要使用%*c ,这是没有必要的。 Second, you need to specify the comma in format string to successfully scan the fields.其次,您需要在格式字符串中指定逗号以成功扫描字段。 Third, when you scanf always check its return value to make sure the expected number fields were input.第三,当您scanf始终检查其返回值以确保输入了预期的数字字段。 Try this fix:试试这个修复:

void read(int *lines, char first[ENTRY][FIRST], char last[ENTRY][LAST], int *num, int *human, float *cool)
{
    FILE *ifile;

    ifile = fopen("hello.txt", "r");
    if (ifile == NULL) return;

    int ret = fscanf(ifile, "%[^,], %[^,], %d, %d, %f", first[0], last[0], &num[0], &human[0], &cool[0]);
    if (ret != 5) { // input file does not match the format
        return;
    }

    printf("%s ", first[0]);
    printf("%s\n", last[0]);
    printf("%d\n", num[0]);
    printf("%d\n", human[0]);
    printf("%f\n", cool[0]);

    fclose(ifile);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM