C/scanf in C
Expert: Zlatko - 1/30/2011
QuestionHi,
I wrote the following program to ask the user to write a sentence and then I want to store each char in the array ch. However I realise by setting i < 128 in the for loop, the user has to type 128 characters before the printf statement is executed. Why won't scanf just end when it reaches end of sentence? Thank you.
int main()
{
int i;
char ch[128];
printf("Enter a message not longer than 128 characters: ");
for (i = 0; i < 5; i++)
{
scanf("%c", &ch[i]);
}
printf("%c", a[2]);
return 0;
}
AnswerHello Pearson
Use %s instead of %c. The %s will cause scanf to read all characters up to the newline. Here is a sample
#include <stdio.h>
int main()
{
char ch[128];
printf("Enter a message not longer than 128 characters: ");
scanf("%s", ch);
printf("%s\n", ch);
return 0;
}