Click to See Complete Forum and Search --> : I want to aassign a value to a char...
Giscardo
09-06-2001, 06:34 AM
In C, i'm trying to assign a value to a char type, i want the ASCII character that corresponds to ascii code 43, so how would i do it?
And also, if i had a char'a', how wouoldi extract the ascii code number from the char?
thanks,
goon12
09-06-2001, 09:42 AM
This is probably not correct but..
#include<stdio.h>
int main()
{
char a;
int b
printf("Enter char a:");
scanf("%c", &a);
printf("Ascii value of a: %d\n", char a);
printf("Enter the int: ");
scanf("%d", &b);
printf("Ascii value of %d: %c\n" b, b);
exit ();
}
[ 06 September 2001: Message edited by: goon12 ]
TheLinuxDuck
09-06-2001, 10:02 AM
Giscardo:
A char is pretty much just an int with a range of -128 to 127 for signed, and 0 to 256 for unsigned. If you assigned a number, such as 43, as:
char c=43;
: then the char is technically both 43 and '+'.
#include <stdio.h>
//
int main(void)
{
char c=43;
printf("c is %d, or '%c'\n",c,c);
return 0;
}
c is 43, or '+'
bwkaz
09-06-2001, 01:27 PM
(/me echoes TLD, and adds this: )
If you know that you are always going to use ASCII code 43, and you know what the character is, then you could also use:
char c='+';
Then using "c" in an expression will end up getting the ASCII value 43 and, say, adding 57 (if the expression is "c + 57"). Again, as TLD said, it's both 43 and '+'. Usually it's 43, but it gets interpreted as '+' when it's printf("%c")'ed.
Not sure if you knew that (I would think you did), but I'll say it anyway, because others may not.
Edit: colon-paren got changed to a smiley, I changed it back
[ 06 September 2001: Message edited by: bwkaz ]
f'lar
09-06-2001, 09:00 PM
Perhaps it would help if you told us why you needed to do this. Why not just char c = '+';?
If you want to know the ascii value for a character variable, just typecast it:
char c='A';
cout << (unsigned int)c;
would output 65 to the screen, not A.
[edit]
oops: you said C, not C++, so I don't know if the typecasting thing will help you much. The cout << statment definitely won't.
[ 06 September 2001: Message edited by: f'lar ]
Giscardo
09-07-2001, 02:39 PM
Well I don't necessarily need a char of 43 (+). The thing is I know java very well, but I'm writing my first C program right now, making a program that converts a number from one base to another base (say, binary to hex, or base three to base 30). And since our decimal system only has ten digits, I needed to map the alphabet from a to z to correspond to 10-36.
The assignment was a lab for one of my CS classes. Thanks for your help guys, I finished the program last night, after a lot of experimenting. I couldn't pass the thing as a char to my mapping function, had to pass it as an int for some reason. But at least it's working now.