June 19th, 2013, 06:21 AM
Type error when reading input from file
I tried echoing an input from a text file using this code.
in my text file.
However, the program printed
I tried different letter encodings, but that didn't seem to be the problem.
June 19th, 2013, 09:58 AM
June 19th, 2013, 11:20 AM
046, it works for me just as you posted it:
I'm using MinGW gcc version 2.95.3-6 (mingw special). What compiler are you using?
BTW, when I use DRK82's suggestion, I get a new warning:
That warning on line 9 is because you left out the return 0;.
While that l ("ell") does not belong with the f in the printf, it is still absolutely necessary in the scanf.
June 19th, 2013, 03:14 PM
I use GNU GCC compiler (or mingw32-gcc.exe; I'm not exactly sure which answer you were asking).
I ran gnu --version and got
so I think the version is 4.7.1.
June 19th, 2013, 03:35 PM
I just re-read your opening post more closely. You are talking about reading a value in from a text file, but your program reads a value from the keyboard. What you are talking about is not what your program would do. Instead, in order for your program to read from a text file, you would need to fopen that file and fscanf to read from it and fprintf to write to it.
Now, what would happen if the fscanf fails? The value of x would remain unchanged. Since it started out containing garbage (whatever just happened to be in that memory location from before), then when you try to print it out it would try to print out that garbage value. What puzzles me in this case is that you are telling us that it's in integr format instead of the floating-point that your code suggests.
Try adding this to your program to debug it:
The return value of *scanf tells you how many conversions succeeded. Since you are trying to read and convert one value, it should return 1. If it returns a different value (eg, zero), then that conversion failed.
. . .
result = fscanf(fp, "%lf", &x);
if (result == 1) // successfully read value
else // failed to read value
printf("fscanf failed: %d conversions\n", result);
June 19th, 2013, 03:46 PM
changing to fopen to fscanf worked.
but what I wanted to do at first was redirect input from the command line.
this is why I have scanf instead of fscanf.
at first, I had input redirection from the command line and reading files into the program mixed up, so I asked a question [url = http://forums.devshed.com/c-programming-42/help-with-batch-mode-947065.html]here[/url].
from the answer given, I thought I was supposed to post the code I posted in the first post of this thread, and redirect input by executing
however, the result was as explained.