954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

need help with atoi

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

hosh
Newbie Poster
4 posts since Oct 2009
Reputation Points: 10
Solved Threads: 0
 

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);
Aia
Nearly a Posting Maven
2,392 posts since Dec 2006
Reputation Points: 2,224
Solved Threads: 218
 
hosh
Newbie Poster
4 posts since Oct 2009
Reputation Points: 10
Solved Threads: 0
 
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 asmall 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' <= <em>character</em> <= '9'

You can check on this by using theisdigit() 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 thectype.h header in order to use the isdigit() function.

tux4life
Nearly a Posting Maven
2,350 posts since Feb 2009
Reputation Points: 2,134
Solved Threads: 243
 

Thank you guys.
Now it makes sense...

hosh
Newbie Poster
4 posts since Oct 2009
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You