简体   繁体   中英

fprintf inside a for loop is not working properly

I am attempting to create a text file using C that will contain a table of values in Fahrenheit and their Celsius conversion. I am able to use fprintf properly outside of the for loop but when I put it inside it does not print anything to the file. The code compiles properly but when I try to execute it completes but with exit code "-1073741819"

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main()
{

    FILE *filePointerThree;
    double myArray[100];

    filePointerThree = fopen("myFileFive.txt", "w");

    for(int i=0; i<=100; i++)
    {
        myArray[i] = (i-32)/1.8;
    }

    for(int j=0; j<=100; j+=5)
    {
        fprintf(filePointerThree, "%d degrees F \t %5.2lf degrees C\n", j, myArray[j]);
    }
    fclose(filePointerThree);
}

Your array needs to be larger to hold 101 values (0 through 100):

    double myArray[101];

Upon further review, the code can be simplified to not require an array, as follows. A return 0; at the end of main() will ensure an exit code of 0. Minor: the math.h and stdlib.h includes are not required as fopen() and friends are defined in stdio.h .

#include <stdio.h>

int main()
{
    FILE *filePointerThree;

    filePointerThree = fopen("myFileFive.txt", "w");

    for(int j=0; j<=100; j+=5)
    {
        fprintf(filePointerThree, "%d degrees F \t %5.2lf degrees C\n", j, (j-32)/1.8);
    }

    fclose(filePointerThree);

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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