繁体   English   中英

当我尝试使用 .txt 文件时,.exe 程序崩溃

[英].exe program crashes when I try to work with a .txt file

我正在尝试读取 .txt 文件。 任务是读取温度并给出最小值、最大值和平均值。 txt 文件称为 Temp.txt,它看起来像这样:

5 76 56 34 35 10
4 45 23 24 14
0
2 32 34 

这是我编写的代码。 我也尝试使用像'fopen(“Temp.txt”,“r”)'这样的文件名来运行它,但我得到了相同的结果。

#include<stdio.h>
#include<string.h>

int ReadTempFile(FILE *fp, float temperatur[]);
float maxTemp(int anzahl, float temperatur[]);
float minTemp(int anzahl, float temperatur[]);
float mittlereTemp(int anzahl, float temperatur[]);
float fahrenheit(float celsius);

int ReadTempFile(FILE *fp, float temperatur[])    //For reading individual rows from txt file
{
    int i=0;
    fscanf(fp,"%f", &temperatur[0]);
    for(i = 0; i < temperatur[0]; ++i)
    {
        fscanf(fp, "%f", &temperatur[i+1]);
    }
    return temperatur[0];
}

float maxTemp(int anzahl, float temperatur[])    //Maximum Temperature
{
    int i = 0;
    float max;
    max = temperatur[i+1];
    for(i = 1; i < anzahl; i++)
    {
        if(temperatur[i+1] > max)
        {
            max = temperatur[i+1];
        }
    }
    return max;
}

float minTemp(int anzahl, float temperatur[])    //Minimum Temperature
{
    int i = 0;
    float min;
    min = temperatur[i+1];
    for(i = 1; i < anzahl; i++)
    {
        if(temperatur[i+1] < min)
        {
            min = temperatur[i+1];
        }
    }
    return min;
}

float mittlereTemp(int anzahl, float temperatur[])    //Average Temperature
{
    int i, sum = 0;
    float mit;
    for (i = 0; i <= anzahl; i++)
    {
        sum += temperatur[i];
    }
    mit = sum/temperatur[0];
    return mit;
}

float fahrenheit(float celsius)    //Celsius to Fahrenheit
{
    float f;
    f = (celsius*9/5) + 32;
    return f;
}


int main()
{
    int end, n, Zeile=1;
    float temperatur[20], max, min, mit, fmax, fmin, fmit;
    char eingabe[20];
    FILE *fp=NULL;
    do
    {
        printf("Enter File name: \n");    //Enter file name
        fflush(stdout);
        scanf("%s", eingabe);
        fp = fopen(eingabe, "r" );
        if(fp == NULL) printf ("Error: File %s can't be opened!\n", eingabe);    //Error message for File cant be opened
    }while(fp != NULL);

    do{
        n = ReadTempFile(fp, temperatur);

        max = maxTemp(n, temperatur);
        printf("Das Maximum der Zeile %d ist: %.3fC \t",Zeile, max);

        fmax = fahrenheit(max);
        printf("In Fahrenheit: %.3fF\n", fmax);

        min = minTemp(n, temperatur);
        printf("Das Minimum der Zeile %d ist: %.3fC \t",Zeile, min);

        fmin = fahrenheit(min);
        printf("In Fahrenheit: %.3fF\n", fmin);

        mit = mittlereTemp(n, temperatur);
        printf("Der Mittelwert der Zeile %d ist: %.3fC \t",Zeile, mit);

        fmit = fahrenheit(mit);
        printf("In Fahrenheit: %.3fF\n", fmit);

        ++Zeile;

        end = feof(fp);
        printf("\n\n");
    }while (end == 0);

    fclose(fp);
    return 0;
}

这是我运行上述程序后发生的情况。

先感谢您。

可能导致崩溃的最直接问题是打开文件的逻辑:

do
{
    printf("Enter File name: \n");    //Enter file name
    fflush(stdout);
    scanf("%s", eingabe);
    fp = fopen(eingabe, "r" );
    if(fp == NULL) printf ("Error: File %s can't be opened!\n", eingabe);
}while(fp != NULL);   // <- Loops until it fails

这将保证在文件无法打开之前循环不会结束。 当您稍后尝试将fscanffp设置为NULL时,您将有未定义的行为(这可能表现为崩溃)。

建议修复:

for(;;) {
    puts("Enter File name:");
    if(scanf("%19s", eingabe) == 1) { // make sure scanf succeeds
        fp = fopen(eingabe, "r" );
        if(fp) break;                 // break out when it succeeds to open
        perror(eingabe);
    } else {
        fprintf(stderr, "Error: No filename entered.\n");
        return 1;
    }
}

注意:在您的示例运行中,您表明您输入了Temp以打开Temp.txt 您必须输入Temp.txt才能成功打开Temp.txt


这是您的程序以及其他一些修复程序。 我已经评论了内联,所以你明白我为什么建议改变。

笔记:

  • 我已经完全消除了temperatur中的+1偏移。 您不应该使用第一个float来存储整数值的温度计数。
  • 你的mittlereTemp没有使用这个偏移量,所以它也给出了错误的答案。
  • mittlereTemp没有计算中值温度(我认为“mittlereTemp”的意思)。 它试图计算平均温度,因此我将名称更改为durchschnittsTemp
#include <math.h>
#include <stdio.h>
#include <string.h>

// For reading individual rows from txt file
// max_anzahl added to not try to read too many
int ReadTempFile(FILE* fp, float temperatur[], int max_anzahl) {
    int count;
    // return -1 on failure
    if(fscanf(fp, "%d", &count) != 1) return -1;

    // we can't read all the entries if count > max_anzahl
    if(count > max_anzahl || count < 0) return -1;

    for(int i = 0; i < count; ++i) {
        if(fscanf(fp, "%f", &temperatur[i]) != 1) {
            return -1; // could not read count floats, failure
        }
    }

    return count;
}

// The idiomatic way is to have the array pointer first and
// the count second so I swapped the order of temperatur and anzahl:
float maxTemp(float temperatur[], int anzahl) {
    if(anzahl == 0) return NAN; // if we have no values, we have no max temp

    float max = temperatur[0];

    for(int i = 1; i < anzahl; i++) {
        if(temperatur[i] > max) {
            max = temperatur[i];
        }
    }
    return max;
}

float minTemp(float temperatur[], int anzahl) {
    if(anzahl == 0) return NAN; // if we have no values, we have no min temp

    float min = temperatur[0];

    for(int i = 1; i < anzahl; i++) {
        if(temperatur[i] < min) {
            min = temperatur[i];
        }
    }
    return min;
}

// I changed the name to durchschnittsTemp
float durchschnittsTemp(float temperatur[], int anzahl) {
    if(anzahl == 0) return NAN; // if we have no values, we have no average temp

    float sum = 0.f;            // use the proper type for sum

    for(int i = 0; i < anzahl; i++) {
        sum += temperatur[i];
    }
    return sum / (float)anzahl;
}

float fahrenheit(float celsius) {
    float f;
    f = (celsius * 9 / 5) + 32;
    return f;
}

// since opening the file is a lot of code, make a function
FILE* open_file_supplied_by_the_user() {
    char eingabe[FILENAME_MAX]; // make plenty of room for the filename
    for(;;) {
        puts("Enter File name:");
        // use fgets instead of scanf to make it easier to read filenames with spaces
        if(fgets(eingabe, sizeof eingabe, stdin)) {
            size_t len = strlen(eingabe);
            eingabe[len - 1] = '\0';
            FILE* fp = fopen(eingabe, "r");
            if(fp) return fp; // break out when it succeeds to open
            perror(eingabe);  // give the user a proper error message
        } else {
            fprintf(stderr, "Error: No filename entered.\n");
            return NULL;
        }
    }
}

#define Size(x) (sizeof(x) / sizeof *(x))

int main() {
    FILE* fp = open_file_supplied_by_the_user();
    if(fp == NULL) return 1; // exit if no file was opened

    float temperatur[20];

    // loop until ReadTempFile() returns -1 (failure)
    for(int n, Zeile = 1;
        (n = ReadTempFile(fp, temperatur, Size(temperatur))) != -1;
        ++Zeile)
    {
        float max = maxTemp(temperatur, n);
        printf("Das Maximum der Zeile %d ist: %.3fC \t", Zeile, max);
        printf("In Fahrenheit: %.3fF\n", fahrenheit(max));

        float min = minTemp(temperatur, n);
        printf("Das Minimum der Zeile %d ist: %.3fC \t", Zeile, min);
        printf("In Fahrenheit: %.3fF\n", fahrenheit(min));

        float mit = durchschnittsTemp(temperatur, n);
        printf("Der Durchschnittswert der Zeile %d ist: %.3fC \t", Zeile, mit);
        printf("In Fahrenheit: %.3fF\n", fahrenheit(mit));

        printf("\n\n");
    }

    fclose(fp);
}

暂无
暂无

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

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