从 .txt 文件中计算数字

标签 c file-io

我正在尝试编写一个函数来输出文件 grade_data.txt 中的数字计数。我遇到的问题是让它在每次将数字写入虚拟变量时正确读取文件以计算每个数字。 dgrade_data.txt 包含整数值,例如: 89 73 95 48岁 66 90后 83 79

我尝试使用:

int temp; while (fscanf(fpin, "%d", temp) != EOF) count++;

但是,这给我带来了与原始代码相同的问题。

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

int main(void) {
    FILE *fpin,;
    fpin = fopen("grade_data.txt", "r");
    if(fpin = NULL) {
        printf("FILE DOES NOT EXIST");
        exit(0);
    }

    printf("Number of students:\t%d", fcount());
    fclose(fpin);
}

int fcount(void){
    int count;
    char c;
    FILE *fpin;
    fpin = fopen("grade_data.txt", "r");

    if (fpin = NULL) {
        printf("FILE DOES NOT EXIST");
        exit(0);
    }
    // Extract characters from file and store in character c 
    for (c = getc(fpin); c != EOF; c = getc(fp)) 
        if (c != '\n' && c ) 
        // Increment count if this character is newline 
        count = count + 1

    fclose(fpin);
    return count;
}

我希望上述数据的输出为 7,但是,我不断收到一个错误,告诉我程序已停止工作

最佳答案

首先,您在 main() 和函数中打开文件两次。然后,函数被放置在 main() 下面而不是上面,所以我想你得到的错误是函数没有被声明。除此之外,您还没有声明 fp,所以我假设您的意思是 fpin。那么,为什么要在 for 循环中两次使用 getc() 呢?这导致读取的第一个字符被丢弃。一个 do-while 循环就足够了:

do
{
    c = getc(fpin);
    if (c != '\n' && c) count++;
    // Increment count if this character is newline <--You are doing the exact opposite
}while(c!=EOF)

这个循环正在读取单个字符,所以我怀疑这是你想要它做的。 如果您改用它,程序应该可以正常运行:

int temp;
while (fscanf(fpin, "%d", &temp) != EOF) count++;

关于从 .txt 文件中计算数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57210582/

相关文章:

c - malloc 灾难性地失败

C程序-如何检查数组元素

java - 传统 IO 与内存映射

c - 如何通过 block 设备打开文件

c++ - 通过 curl 通过 http 发送和接收字符串

C - 创建链表的函数仅返回第一个节点

堆损坏错误 c

c# - 在 C# 中监视文件/目录访问

c++ - 存储和检索动态变化的结构

c - fseek 和 fwrite 过去的 EOF