Hi,
can anyone help me to solve this problem?
I have this code:

``````FILE *in;
char  i =fgetc(in);
int perm=0;
perm =atoi(&i);
printf("%d\n", perm);``````

if first character in my "in" file is 2, the output is 28;
if ------------------------------- is 3, -------------- 38, and so on...

any ideas what is wrong with this code?
thanks

Edited by WaltP: Added CODE tags -- with all the help about them, how could you miss using them????

3
Contributors
4
Replies
5
Views
8 Years
Discussion Span
Last Post by hosh

Hi,
can anyone help me to solve this problem?
I have this code:

FILE *in;
char i =fgetc(in);
int perm=0;
perm =atoi(&i);
printf("%d\n", perm);

if first character in my "in" file is 2, the output is 28;
if ------------------------------- is 3, -------------- 38, and so on...

any ideas what is wrong with this code?
thanks

atoi() accepts a string as argument. Not a character `i` as it is in your code, nor a pointer to a char like you give it as in `atoi(&i)` Something like:

``````char twenty_three[] = "23";
int result;

result = atoi(twenty_three);``````

Edited by Aia: n/a

.

Edited by hosh: n/a

any ideas what is wrong with this code?

What exactly is the purpose of your code?
To me it seems like you're reading a file character by character, and then printing out only the digits?

Why doing a conversion to integer if you only want to print the digits out?

``````char c = fgetc(in); /* read character */
if( isdigit(c) )    /* if character is a digit */
putchar( c );    /* print character */``````

Also, if you want to do a conversion to integer for only one digit, then you can use a small trick:

``````char c = '5';
int i = c - '0'; /* i now contains: 5 */``````

Please note that you should only apply this trick when you're sure the character variable of which you're subtracting the ASCII value of zero holds a character which is in this range: `'0' <= [I]character[/I] <= '9'` You can check on this by using the isdigit() function:

``````int i;
char c = '9';

if( isdigit( c ) )
i = c - '0'; /* i now contains: 9 */``````

But again, in your case it seems to me like you don't need a conversion, as it seems like you're just printing digits on your screen, nothing else.

Note: you'll need to include the ctype.h header in order to use the isdigit() function.

Thank you guys.
Now it makes sense...

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.