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?
iuxAsked:
Who is Participating?
 
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
 
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
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

 
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.