简体   繁体   中英

How to save a char to an array in the position of its ascii num In c

I am working on a Caesar cipher and I am trying to save the characters of my cipher key in an array based on the ascii of the letter is supposed to represent. So if my cipher char key[] = "codezyxwvutsrqpnmlkjihgfba" The first char in the array (c) is supposed to represent the letter a, whose ascii num is 97. So I want to store c in the array in the 97th spot. Everytime I try to this the array turns out empty.

char key[] = {"codezyxwvutsrqpnmlkjihgfba"};

char alphabet[] = {"abcdefghijklmnopqrstuvwxyz"};

char answerKey[200] = "";

for (int i = 0; key[i] != '\0'; i++) {
    answerKey[(int) alphabet[i]] = key[i];
}

for (int i = 0; answerKey[i] != '\0'; i++) {
    printf("%c", answerKey[i]);
} 

Since the answerkey array has values only in the range of 97 - 122 assuming you are only using lower alphabet the other elements of the arrays are garbage.

Just change the print for loop to iterate from 97 to 122 and you get what you want.

char key[] = {"codezyxwvutsrqpnmlkjihgfba"};

char alphabet[] = {"abcdefghijklmnopqrstuvwxyz"};

char answerKey[200]="";

for (int i = 0; key[i] != '\0'; i++) {
    printf("%c",alphabet[i]);
    answerKey[(int) alphabet[i]] = key[i];
    printf("%c",answerKey[(int)alphabet[i]]);
}
printf("\n");
int i=0;
for (i = 97;i<=122; i++) 
{
    printf("%c", answerKey[i]);
} 

You are starting your printing of the answerKey[] array at the first element and telling it to stop as soon as it hits '\\0' . I don't believe answerKey[0] should ever not be '\\0' since none of the printable ascii characters are 0. I would expect your answerKey[] array to be empty except between elements 97-122, so if your cipher will be used only for lowercase alphabetical characters, perhaps only look in that part of the array.

Alternatively, you could make your answerKey[] array only hold enough space to fit your cipher by subtracting 'a' from the element address as you're placing it. Something like this might do the trick:

char answerKey[27] = "";

for (int i = 0; key[i] !='\0'; i++) {
    answerKey[(int) alphabet[i] - 'a'] = key[i];
}

In C, you can convert a char to an int by simply preforming a cast.

In the memory, when you have a char 'a', the value 97 is saved. When you use a char, it is just the way you understand what is written in the memory. you can just treat this memory as an int, and get the value which is stored over there.

For example:

char c = 'a';
printf("char is %c, int is %d", c, (int)(c));
// Output would be:
//   char is a, int is 97

For further information, read: How are different types stored in memory

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM