How can I add to the ascii value of a char letter? - c

so, lets say that a char contains the letter "a":
int main() {
int i=8;
char test2[2]="a"+i;
return 0;
}
I just want to add 5 to the value of that letter's ASCII value. So that test2 would contain "h", since ASCII value of h a ASCII value of a+8.
Is there a simple way to do this? I have tried googling this, and I would think this is a basic thing to do, but I am clearly missing an easy way to do this. Would appreciate any help.

You have to add to a char, not the string:
char test2[2] = { 'a' + i, 0 };

"a" is not a character, but a string. You need single quotes to works with individual characters.
int i = 8;
char c = 'a' + i;
printf("c=%c\n", c);
Output:
c=i

In C, character holds an ACSII value (which is integer) by default. In your case, to make h out of a you have to do this:
#include <stdio.h>
int main() {
char test2 = 'a' + 7;
printf("%c\n\n", test2); // just check
return 0;
}

Haven't compiled this, but wouldn't (int)'a' + i work?
A double quote isn't a char, its a string literal.

Related

How to get a char from ASCII number

Hello. Im reading file using FILE and reading that using fgetc to read that.
fgetc function returns me int value of my chars in ASCII.
Now i want to print that data in char values.
How to convert my ascii numbers to chars?
You most likely don't need any conversion. If the native character set on your system is ASCII (which is the most common) then no conversion is needed. 'A' == 65 etc.
That means to print a character you just print it, with e.g. putchar or printf or any other function that allows you to print characters.
int x = 48;
printf("%c", x);
it will print 0, also you can do this
int x = 48;
char xx = (char)x;
Specify format as for a char, like so:
printf("%c", number);
printf("%c", 65); // A
#include <stdio.h>
int main()
{
int i;
for (i=97; i <=200 ; i++)
{
printf("%d %c,\t",i,i);
};
return 0;}
This will give you the whole chart upto 200.

How to convert each character in a character array to integer?

I have tried the standard methods but still I get error in my answer.
My code:
int main() {
int val;
char str[] = {'1', '45', '0'};
val = str[1] - '0';
printf("Int value = %d\n", val);
return(0);
}
I am getting answer as 5 instead of 45.
How do I solve this issue?
[update from comment:]
I actually need to process an array of strings..suppose I want to convert octal numbers to decimal, and my input has to be in the form of an array of strings. I wish to convert these no.s to decimal : {45,17,100} For that I would, at first be requiring to extract each element and change it to integer. Could you plz suggest what would be the best way to do it?
I actually need to process an array of strings
What you have defined here
char str[] = {'1', '45', '0'};
is not an array of strings, but exactly one array of char with 3 elements. It is not even a C-"string", as this would require a trailing value of 0. Note that the value of the character '0' isn't 0, but, for example, for the ASCII character set it's 48.
'45' is a multi-byte character literal, which in fact is an integer. The code above tries to initialise the 2nd element of the char-array str (str[1], which is a char) using this very literal.
This does not work.
A char cannot (necessarily) hold the int value of this multi-byte character literal. In this case the initialisation of str[1] overflows, resulting in the unexpected value of 5.
To see the issue try the following code:
#include <limits.h>
#include <stdio.h>
int main(void)
{
char c_min = CHAR_MIN;
char c_max = CHAR_MAX;
unsigned char uc = '45';
printf("'1'=%d\n", '1');
printf("'45'=%d\n", '45');
printf("'0'=%d\n", '0');
printf("lowest possible value for char=%d\n", c_min);
printf("highest possible value for char=%d\n", c_max);
printf("'45' converted to an (unsigned) char=%u\n", uc);
return 0;
}
The example above shows how the value of 45 gets truncated when being assigned to char.
Depending on the C implementation you use the conversion of '45' to a char might even invoke the infamous Undefined Behaviour. This is not good.
What you seem to be wanting is:
#define ARRAY_SIZE_MAX 3
char * str[ARRAY_SIZE_MAX] = {"1", "45", "0"}; /*. Mind the double quotes. */
This defines an array of 3 pointers to char , with each pointing to a C-"string".
Here, you are getting 5 instead of 45 because st[1] = '5', this is because we have only ASCII value of 0 to 9 integers and 45 have no ASCII value.
To store 45 in your string you have to declare multidimensional string.
for example:
char st[3][3]={'1', '45', '0'};
Here is the working code:
#include<stdio.h>
int main(){
int i,ans,j;
char st[3][3]={{'1'}, {'4','5'},{'0'}};
for(j=0;j<3;j++){
for(i=0;st[j][i]>=48 && st[j][i]<=57;i++){
ans=st[j][i]-'0';
printf("%d",ans);
}
printf("\n");
}
return 0;
}
Output is
1
45
0
It depends, what do you want.
Every character has it's own int value- It's simply ASCII code
If you will iterate over integers and make it print like %c you will get ASCII table (you can see it eg. there.
But if you want to read int values from string / char datatype you will have to parse it- atoi (ascii to integer) function- example there
Btw I dont know how exactly your example works but the problem is you are doing following: int val = '45' - '0'; int value of '0' should be 48, '45' rly I dont know, but '4' is 52int and '5' is 53 int, so something like that..
As i wrote you should to do something like int val = atoi('45') - atoi('0') just for sure maybe better to cast into int as follows int val = (int) (atoi('45') - atoi('0')) - exactly asi in your example
int main() {
int val;
char str[] = {'1', '45', '0'};
val = (int) (atoi(str[1]) - atoi('0'));
printf("Int value = %d\n", val);
return(0);
}
Not sure, but i think that should works, hope that will help

Can i assign a integer to a character pointer array?

int k=5;
char* result = (char *)malloc(100 * sizeof(char));
result[count] = k;
Considering the above code, if I print the contents of result[count] it prints smiley symbols. I tried like below,but of no use.
result[count]=(char)k;
Can anyone help me?
I am percepting that malloc(100*sizeof(char)) will create 100 blocks each of size of character contiguously. Please correct me if I am wrong?
I'll disregard all the fluff about arrays and malloc as it is irrelevant to the problem you describe. You seem to essentially be asking "What will this code print:"
char c = 5;
printf("%c", c);
It will print the symbol 5 in your symbol table, most likely a non-printable character. When encountering non-printable characters, some implementations choose to print non-standard symbols, such as smileys.
If you want to print the number 5, you have to use a character literal:
char c = '5';
printf("%c", c);
or alternatively use poor style with "magic numbers":
char c = 53; // don't write code like this
printf("%c", c);
It is a problem of character representation. Let's begin by the opposite first. A char can be promoted to an int, but if you do you get the representation of the character (its code). Assuming you use ASCII:
char c = '5';
int i = c; // i is now 0x35 or 53 ASCII code for '5'
Your example is the opposite, 5 can be represented by a char, so result[count] = k is defined (even if you should have got a warning for possible truncation), but ASCII char for code 5 is control code ENQ and will be printed as ♣ on a windows system using code page 850 or 437.
A half portable (not specified, but is known to work on all common architectures) way to do the conversion (int) 5 -> (char) '5' is to remember that code '0' to '9' are consecutive (as are 'A' to 'Z' and 'a to 'z'), so I think that what you want is:
result[count] = '0' + k;
First, let's clean up your code a bit:
int k=5;
char* result = malloc(100);
result[count] = k;
sizeof(char) is always equal to 1 under any platform and you don't need to cast the return of malloc() in C.
This said, as long as your count variable contains a value between 0 and 99, you're not doing anything wrong. If you want to print the actual character '5', then you have to assign the ASCII value of that character (53), not just the number 5. Also, remember that if that array of chars has to be interpreted as a string, you need to terminate it with '\0':
int k=5, i;
char* result = malloc(100);
for (i=0; i<98; i++) {
result[i] = ' ';
}
result[98] = 53;
result[99] = '\0';
printf("%s\n", result);
The elements in the array you're trying to allocate are all the size of a char, 1 byte. An int is 4 bytes thus your issues. If you want to store ints in an array you could do:
int result[100];
Followed by storing the value, but honestly from the way your questioned is posed I don't know if that's actually what you're trying to do. Try rephrasing the post with what you're trying to accomplish.
Are you trying to store 5 as a character?

converting integers to chars in C(according to ASCII table)

been searching everywhere, but couldn't the correct answer.
the problem is pretty simple:
i have to convert ASCII integer values into char's.
for example, according to ASCII table, 108 stands for 'h' char. But when i try to convert it like this:
int i = 108
char x = i
and when I printf it, it shows me 's', no matter what number i type in(94,111...).
i tried this as well:
int i = 108;
char x = i + '0'
but i get the same problem! by the way, i have no problem in converting chars into integers, so i don't get where's the problem :/
thanks in advance
That is how you do it. You probably want it unsigned, though.
Maybe your printf is wrong?
The following is an example of it working:
// Print a to z.
int i;
for (i = 97; i <= 122; i++) {
unsigned char x = i;
printf("%c", x);
}
This prints abcdefghijklmnopqrstuvwxyz as expected. (See it at ideone)
Note, you could just as well printf("%c", i); directly; char is simply a smaller integer type.
If you're trying to do printf("%s", x);, note that this is not correct. %s means print as string, however a character is not a string.
If you do this, it'll treat the value of x as a memory address and start reading a string from there until it hits a \0. If this merely resulted in printing s, you're lucky. You're more likely to end up getting a segmentation fault doing this, as you'll end up accessing some memory that is most likely not yours. (And almost surely not what you want.)
Sounds to me like your printf statement is incorrect.
Doing printf("%c", c) where c has the value 108 will print the letter l... If you look at http://www.asciitable.com/ you'll see that 108 is not h ;)
I'm guessing your printf statement looks like this:
printf("s", x);
..when in fact you probably meant:
printf("%s", x);
...which is still wrong; this is expecting a string of characters e.g:
char* x = "Testing";
printf("%s", x);
What you really want is this:
int i = 108;
char x = i + '0';
printf("%c", x);
...which on my system outputs £

Simple int to char[] conversion

I have a simple question
How to simply convert integer (getting values 0-8) to char, e.g. char[2] in C?
Thanks
main()
{
int i = 247593;
char str[10];
sprintf(str, "%d", i);
// Now str contains the integer as characters
}
Hope it will be helpful to you.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main()
{
int a = 543210 ;
char arr[10] ="" ;
itoa(a,arr,10) ; // itoa() is a function of stdlib.h file that convert integer
// int to array itoa( integer, targated array, base u want to
//convert like decimal have 10
for( int i= 0 ; i < strlen(arr); i++) // strlen() function in string file thar return string length
printf("%c",arr[i]);
}
Use this. Beware of i's larger than 9, as these will require a char array with more than 2 elements to avoid a buffer overrun.
char c[2];
int i=1;
sprintf(c, "%d", i);
If you want to convert an int which is in the range 0-9 to a char, you may usually write something like this:
int x;
char c = '0' + x;
Now, if you want a character string, just add a terminating '\0' char:
char s[] = {'0' + x, '\0'};
Note that:
You must be sure that the int is in the 0-9 range, otherwise it will fail,
It works only if character codes for digits are consecutive. This is true in the vast majority of systems, that are ASCII-based, but this is not guaranteed to be true in all cases.
You can't truly do it in "standard" C, because the size of an int and of a char aren't fixed. Let's say you are using a compiler under Windows or Linux on an intel PC...
int i = 5;
char a = ((char*)&i)[0];
char b = ((char*)&i)[1];
Remember of endianness of your machine! And that int are "normally" 32 bits, so 4 chars!
But you probably meant "i want to stringify a number", so ignore this response :-)

Resources