Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

char --> short

Status
Not open for further replies.

SotonStu

Programmer
May 7, 2003
33
0
0
GB
How do i convert a char to a short?
 
hi, simply

char c;
short int w ; // see your compiler for exact way

w = c ;

or if your compiler is rigorous, say it:

w = (short int) c ;

bye
 
that doesn't seem to work, for instance, if i say:

char test = '9';
short w;
w = test;
cout << w;

the output is: 57
obviously this is an error and all other shorts i try to convert in this way come up erroneously.
 
hi,
I understand your ascii-int misconfusion.

What I sayd, is true if

c=9 ;
w=c ;

print w -> 9


If you write

c = '9', you mean the ascii value of the character 9;

if you take an ascii table of chars you can see some
essential value as

' ' -> 32
'0' -> 48 ( then '9' => 48+9=57 )
'A' -> 65

In C language you can write

int i ;

i= '0' + '9' ;

if you printf( &quot;%d\n&quot;, i ); you'll see 105

bye
 
i'm taking the value in through the argument, so that argv[1] is &quot;8 C&quot; (i'm playing around with a cards simulation). I'm putting argv[1] into a string then trying to say, short test = mystring[0];
how can i get the real value, rather than the ascii-character value?
 
hi,
if you are sure that your number is less than 10,
you can

char mystring[16];
int i ;

strcpy( mystring, argv[1] );

i = mystring[0] - '0' ;

or i = *(argv[1]) - '0' ;

If your command line may be: myprog &quot;10 C&quot;, use

sscanf( argv[1], &quot;%d&quot;, &i )
or i=atoi(argv[1])

bye
 
The simplest way is to say:
Code:
char c = '9';
short int n = c - '0';

If 57 is the ASCII value of '9' and 48 is the ASCII value of '0', then n will be assigned 57 - 48, which is 9. This will work for any ASCII digit character.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top