You are here:

C/scanf in C

Advertisement


Question
Hi,
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;
}

Answer
Hello 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;
}

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.