Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 874
  • Last Modified:

char convert

hi,
i  wanna convert  char,which is read from a  data, convert  into the type  int.
i have tried  
(int)char;
and
int tmp; tmp = char;
but  it returns the ASCII number,
emaple: char  ch = '6';
(int)ch = 54

how can i do it?
and which head date should i add?
0
iux
Asked:
iux
1 Solution
 
tinchosCommented:
Try using

#include <stdlib.h>


char number = '6';
int temp = atoi( number );

and in temp will be equal to 6

Hope this helps

Tincho
0
 
iuxAuthor Commented:
hmmmmmmmmmmm
it  says
invalid conversion from `char' to `const char*'
0
 
itsmeandnobodyelseCommented:
No, atoi wants a char* - char pointer - and not a single char.

if you have a single digit in a char you may do this:

  char c = '9';

  int    i  = c - '0';

maybe you should check before:

   if (c >= '0' && c <= '9')
   {
        int i = c - '0';
        ...
   }

if you have a number and not a digit, you may use atoi

   char cn[] = "123";   // that i a zero-terminated string
   int    i      = atoi(cn);

Regards, Alex


0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
rstaveleyCommented:
char number = '6';
int temp =  number-'0';
0
 
RJSoftCommented:
#define MAX ??
char arr[MAX];
char number='6';
arr[0]=number;
arr[1]='\0';

int val = atoi(arr);

RJ
0
 
n_fortynineCommented:
rstaveley's solution is simple and clean. Why go through all these complexity? :D
0
 
iuxAuthor Commented:
ok
i try it
thanks a lot
0
 
void_mainCommented:
... and what will you do if the number is something like this: 12345 ???

this will not work 'cause "12345" is not a single char!

therefore this will do it, and even with one char!

look:


char *number = "12345";
int realNumber = atoi(number);

but don't do this:
char *number = '12089';
or
char *number = '2';

best regards
void_main
0
 
iuxAuthor Commented:
thx :-)
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now