C - 使用 sscanf 读取多个整数和 float

标签 c file integer fgets scanf

我正在为我的 C 编程课做一道练习题,它告诉我编写一个程序,从文件中读取变量。在第一行,它应该读入一个整数 N。

从那里开始,它应该读取一个整数,然后在 N 行的每一行上读取五个 float 。它应该计算文件中所有 float 的总和并将其写入另一个文件。

我编写了一个程序,它应该使用 fgets 将一行复制到一个字符串,然后使用 sscanf 对其进行剖析并将段分配给不同的数组位置。但是,我在通过 sscanf 获取无关信息时遇到了一些问题(可能是空值或换行符)。它没有正确存储整数 N(它产生了很大的随机值并通过无限循环产生了运行时错误),而且它可能也没有在循环内部工作。

我怎样才能完善它以使其正确读取整数和 float ?

#include <stdio.h>
#include <stdlib.h>

#define MAX_STRING 30
#define MAX_LINE_SIZE 200

int main(void)
{
    FILE *f1, *f2;
    char filename[MAX_STRING];
    char fileline[MAX_LINE_SIZE];
    int N, eN;
    float totalwage = 0;
    int* ssn;
    float** wage;

    printf ("Enter a file name for data analysis: ");
    scanf ("%s", &filename); //get file name from user input for reading

    f1 = fopen (filename, "r");

    fgets (fileline, MAX_LINE_SIZE, f1); //read first line
    sscanf (fileline, "%d", &N); //pull integer from first line to determine how many lines follow

    for (eN = 0; eN < N; eN ++) //read N lines following the first
    {
        // VVV read single line from file
        fgets (fileline, MAX_LINE_SIZE, f1);
        // VVV record data from line
        sscanf (fileline, "%d, %f, %f, %f, %f, %f", &ssn[eN], &wage[eN][0], &wage[eN][1], &wage[eN][2], &wage[eN][3], &wage[eN][4]);
        // VVV add the 5 wages on each line to a total
        totalwage += wage[eN][0] + wage[eN][1] + wage[eN][2] + wage[eN][3] + wage[eN][4];
    }

    fclose (f1);

    printf ("Enter a file name for the result: ");
    scanf ("%s", &filename); //get file name from user input for writing

    f2 = fopen (filename, "w");

    fprintf (f2, "%f", totalwage); //store total of wages in file specified by user

    printf ("\nThe information has been stored. Press any key to exit.\n");
    getchar();
}

正在读取的文件是'wages.txt',内容如下:

10
1, 10, 20, 30, 40, 50
2, 11, 12, 13, 14, 15
3, 21, 23, 25, 27, 29
4, 1, 2, 3, 4, 5
5, 30, 60, 90, 120, 150
6, 37, 38, 39, 40, 41
7, 40, 50, 60, 70, 80
8, 5, 10, 15, 20, 25
9, 80, 90, 100, 110, 120
10, 1000, 2000, 3000, 4000, 2000

回顾一下,问题是存在运行时错误,其中程序由于某种无限循环而崩溃。通过一些调试,我发现它没有正确地在第一行读取整数。它存储的不是值 10,而是大值,就好像它读取一个空字符一样。


我已添加代码以尝试为 ssn 和工资分配内存。但是,我不确定它是否正确完成,并且该程序仍然存在崩溃运行时错误。

ssn = malloc (N*MAX_STRING);
wage = malloc (N*MAX_STRING);
for (eN = 0; eN < N; eN ++)
{
    wage[eN] = malloc (N*MAX_STRING);
}

最佳答案

您没有为工资分配任何内存。它被声明为指向 float 的指针;很好,但是指针没有指向任何地方。

ssn 也是一样。

在这一行之后:

sscanf (fileline, "%d", &N); //pull integer from first line to determine how many lines follow

需要给ssn和wage分配内存。

因为这是作业,所以我不会告诉你如何分配内存;您需要能够自己解决这个问题。

关于C - 使用 sscanf 读取多个整数和 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19873230/

相关文章:

c - mac os下通过sysctl调用获取/proc/<pid>/map信息

使用 malloc 将 token 复制到二维数组

c++ - 写入文本文件的数据部分损坏且无法恢复

java - 从不同线程从磁盘读取可以优化程序吗?

python - 如何将png文件放入字符串并将其写入另一个文件

binary - 仅使用位逻辑查找二进制中两个整数的最大值

c - 解析特定数字

java - 在 Java 中声明一个 unsigned int

C - 读取一串数字

C getchar() 的误解