Reputation: 2627
I have a problem with a C application; i have on a .txt file some float numbers and I have to read them and sort in descending way. When i do the fscanf command and then the printf, i get on the screen strange numbers (memory location I suppose). How can i solve the problem? Thanks in advance
Edited The application is composed by more than 1200 code lines; here's the problem:
.......
fopen=(fp1,"scores.dat","r")
fopen=(fp2, "team_number.dat", "r")
fscanf(fp2,"%d", &x);
for (i=0;i<x;i++) {
fscanf(fp1,"%f", &punteggi)
printf("%3.1f\n", punteggi)
}
......
Upvotes: 0
Views: 1767
Reputation: 6856
Make sure you give lvalues to the fscanf
(eg not fscanf("...",a);
if a is a float but rather fscanf("...",&a);
)
And that printf
reads the actual numbers and not pointers or lvalues.
Upvotes: 0
Reputation: 36082
The problem using fscanf() to read from a file is that it is very sensitive, if the formatting specifier in some small way doesn't match the data you either get garbage back or a stack/memory overwrite . You don't show how your in-data looks like so its a bit difficult to tell how the format specifier should like .. for instance if you have spaces in between and if there are new line characters - you may need to specify width as well if you don't have spaces in between values.
A more foolproof way is instead to read using fgets() (or fread) and then, if necessary, parse the string using strok() to thereafter convert the tokens to your desired type (atof in your case).
Upvotes: 1