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)
}
......
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).
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.
精彩评论