Reputation: 13
For my task I have to print numbers to the screen and decode them into their specific letters. I'm using only the letters a-l in this code just to keep it simple so I can understand it.
The problem I'm having is that when I, for example, put in the number 0 which corresponds to the first entry to the array which is a, it will take out a and print b-l.
How do I make it so if I put in the number 0, the code will print only a to the screen?
#include <stdio.h>
int main()
{
char code[] = "abcdefghijkl";
int i, j, k;
printf("how many letters does your code contain?: ");
scanf("%d", &j);
for(i=0; i<j; ++i){
printf("enter a number between 0 and 11\n");
scanf("%d", &k);
printf("%s\n", &code[k]);
}
}
Upvotes: 0
Views: 611
Reputation: 900
printf("%c\n", code[k]);
instead of printf("%s\n", &code[k]);
Upvotes: 0
Reputation: 73443
%s
format specifier is used for printing strings, you need to use %c
specifier which prints a character to the screen.
Upvotes: 0
Reputation: 229088
You print only the character at that location, so change
printf("%s\n", &code[k]);
to
printf("%c\n", code[k]);
You should also check that the value you read into k
is >= 0 && < 11 , otherwise you'll access the array outside its bounds.
Upvotes: 4