问题
When I run the program, the numbers I'm getting are completely ridiculous such as -39389014 when the number in the text file is 20. Here is what my text file looks like:
20 20
40 30
80 40
90 20
60 10
18.0
And the Code:
#include <stdio.h>
#define SIZE 5
int main(void){
FILE *in = fopen("pfile1.txt", "r");
int x[5], y[5], i;
double h;
for (i=0;i<SIZE;++i){
fscanf(in, "%d %d", &x[i], &y[i]);
}
for (i=0;i<SIZE;++i){
printf("%4d %10d\n", x[i], y[i]);
}
fscanf(in, "%lf", &h);
printf("%lf\n", h);
fclose(in);
return(0);
}
回答1:
Make sure that your "pfile1.txt" file is placed next to your project settings. to make sure about the place of your file should be, change the permission of open to "w+". This option will try to open that file or create it if not found. The replace that file with yours. Everything will be work without any problem :)
Just Hint on the fly: Don't make any operation on any pointer unless you make sure that it is not NULL. so, surround your code with to avoid any crashing
if( NULL != in)
{
for (i=0;i<SIZE;++i){
fscanf(in, "%d %d", &x[i], &y[i]);
}
for (i=0;i<SIZE;++i){
printf("%4d %10d\n", x[i], y[i]);
}
fscanf(in, "%lf", &h);
printf("%lf\n", h);
fclose(in);
}
来源:https://stackoverflow.com/questions/36189108/very-basic-trying-to-read-from-a-text-file-with-numbers-and-store-them-in-an-ar