# combining digits into a number

Printable View

• 05-12-2007
waxydock
combining digits into a number
Hi,

im getting digits from a file, but i need to know how to combine these digits into a number so i can store it as an int. So for example my file is

1234

i then read digit by digit like so..

current1 = fgetc( inFile ); /* =1 */
current2= fgetc( inFile ); /* =2 */
current3 = fgetc( inFile ); /* =3 */
current4 = fgetc( inFile ); /* =4 */

now how do i form these into a single number again.. is it something like..

int finalnum = current1 +current2 +current3 +current4 + something..;

im not sure.. please help

thanks.
• 05-12-2007
zxcv
atoi converts a char to a int.

Instead of going character by character you could try to reading in a char string, or just keep appending to one you have off to the side. Then run atoi
• 05-12-2007
zacs7
Remember that 1 is not necessarily '1' in ascii

Do what zxcv said, but read it in as a string (or char array) then convert the entire string rather than each char.
• 05-12-2007
ulillillia
1, in ASCII, is actually 49. 48+number gives the actual ASCII position. If you want to read single digits, then you can take the value that is read and subtract 48 from it. To read a group of digits as a single number, read the full string as needed then use atoi or atof, depending on the format you're using.
• 05-12-2007
zacs7
Quote:

Originally Posted by ulillillia
1, in ASCII, is actually 49. 48+number gives the actual ASCII position. If you want to read single digits, then you can take the value that is read and subtract 48 from it. To read a group of digits as a single number, read the full string as needed then use atoi or atof, depending on the format you're using.

Not always, For most 'normal' systems yes. The only thing that *shouldn't* change is the ordering of the table.

So you'd be better to do:

Code:

`signed char val = myvar - '0';`
• 05-12-2007
waxydock
cheers, ill give it ago