0

I am trying to open and read a .txt file that simply contains a 2 digit number from 00 to 99.

Currently the file contains the following numbers: 05

When I read the first two values with fgets(), I instead get 48 and 53, and I've noticed whatever number I put in there, the number that fgets() grabs is 48 higher. While I could just subtract 48 from the number like I am doing now, I would like to figure out what I am doing wrong so that I don't have to do that. Here is the relevant section of my code:

char buff[3];
FILE *fp;
fp = fopen("savedata/save.txt","r");
fgets(buff, 3, fp);
SampleLevelIndex = (buff[0]-48)*10 + buff[1]-48;
fclose(fp);
Jake Ward
  • 15
  • 2
  • 48 is the ASCII code for the character `'4'`. `fgets` does not read numbers. It reads characters. Why don't you use `fscanf`? – DYZ Oct 06 '20 at 23:29
  • Does this answer your question? [Convert char to int in C and C++](https://stackoverflow.com/questions/5029840/convert-char-to-int-in-c-and-c) – DYZ Oct 06 '20 at 23:30
  • So I tried casting it to an int after I read it but that didn't seem to work. Is there another way to do it? – Jake Ward Oct 06 '20 at 23:32
  • You cannon cast a digit character to the numeric value that it represents. See a link to the possible dupe. – DYZ Oct 06 '20 at 23:33
  • @JakeWard casting is not the same as converting from ascii to integer. atoi / atol will do it – pm100 Oct 06 '20 at 23:33
  • That looks like it'll do the trick, thanks a ton. – Jake Ward Oct 06 '20 at 23:35

1 Answers1

1

Your file contain the characters '0' and '5'. Note that the ASCII code for '0' is 48.

You are reading the values of the bytes, not the number represented. If you had an 'A' in the file, you would have the byte 65.

Your approach works for manually converting numeric characters into a number (although you might one some extra checking, it will break if it doesn't contain two numbers). Or you could use a function like atoi() which converts a numeric string into the number.

Ángel
  • 890
  • 7
  • 12