This question already has an answer here:
- When should I use ampersand with scanf() 3 answers
I've been struggling with this for a really long time trying to figure it out, I'm guessing it's a really stupid noob mistake but I can't figure it out.
So I'm trying to read in an integer from a file and then do some operations in it, for the sake of the problem I'm just trying to output it here:
FILE * pFile;
int number;
pFile = fopen ("myfile.txt","r");
if (pFile!=NULL) {
fscanf(pFile, "%d", number);
fclose (pFile);
}
printf("number: %i", number);
return 0;
the contents of myfile.txt:
123
but when I run it it doesnt read it anything instead it says
RUN FAILED (exit value 1, total time: 32ms)
Thanks for any and all help
EDIT: I forgot to mention, it works as a string, it reads the correct number, but I can't do any operations on it, also if I set the number type to double it works but outputs some random number in the millions...
Yor need to have a pointer to number
i.e.
And it is a good idea to check the return value from
fscanf
You also probably need to do a flush.
i.e. After printf add the line
Also you either need to initialise
number
or do areturn
if you are unable to open the file.So in summary the code should look like this
You forgot to pass fscanf the address of number rather than the value of number. So replace
with
It is necessary to pass it the address of/ a pointer to number, because otherwise it cannot modify the contents of number.
Never forget that for inputs (from keyboard/file) you need to mention the address of the variable. So you have to put
&
before the variable.In your case:
Also you'd better check if you reached the End-of-File or not:
Check these manuals for more:
Linux Programmer's Manual
C library function - fscanf()
You need to pass the address of the int variable to fscanf