So I am trying to get a sentence using getchar() and print it out.
I assigned the character I get from getchar() into a char variable and it worked fine.
But when I assigned into character array directly, it looks like the loop never ends and wait for me to input more.
<CODE>
#include <stdio.h>
int main()
{
char a[81];
int i = 0;
printf("Enter a sentence\n");
while( a[i] != '\n')
{
a[i] = getchar();
i++;
}
a[i - 1] = '\0';
printf("%s\n", a);
}
</CODE>
So this code does not work because I used a[i] directly.
Following code works fine.
<CODE>
#include <stdio.h>
int main()
{
char a[81];
int i = 0;
char character;
printf("Enter a sentence\n");
while( character != '\n')
{
character = getchar();
a[i] = character;
i++;
}
a[i - 1] = '\0';
printf("%s\n", a);
}
</CODE>
What's going on???Why can't I just assign it into array ? Why should I go through a variable ?