Why can't I print the space character?
This is my code:
int main(void)
{
int i, j, k, n;
char userLatter, space;
printf("please enter an uppercase letter:\n");
scanf("%c", &userLatter);
n = 9;
for (i = 0; i < 5; i++)
{
space = ' ';
for (j = 5; j > i; j--)
{
++space;
}
for (k = 0; k <= i ; k += 1)
{
printf("%c%c%c", space, userLatter, space);
}
printf("\n");
}
}
Could you please tell me what should I do to print the space character?
Thank!
source to share
You keep turning the space into something else with the line:
++space;
What did you expect from this? You are trying to make it a string with multiple spaces.
You can leave your character with a format specifier printf
. Try the following:
int width = 4;
char letter = 'A';
printf( ":%*c:\n", width, letter );
This will output 3 spaces and the letter A:
: A:
And if you just want to put a space, don't forget that you can just put a space in the format string. As in the famous:
printf( "Hello, world!\n" );
Note that there is a space in there.
source to share
This is not Java. In C
no Strings
. Also, you are using char[]
. You can't tell ++space
and expect space
to concatenate it yourself. ++space
coincides with space = space + 1
in C
. Doing this will add 1 to it the ASCII value if I'm wrong. space
is a char and can only hold char once. If you want it to hold more than one character, you need to make an array. Here's an alternative:
char space[5]; //This would be done at the top when you initialize it
/* Many lines of code later */
for(j = 5; j > i; j--){
space[j] = ' ';
}
FYI that n
doesn't do anything and wastes space. Sorry, my OCD senses tingled.
source to share