2
char c;
int i;
for(i=0;i<5;i++)
{
 printf("Enter a character : ");`
 scanf("%c",&c);
}
getch();

The above code doesn't work properly.It is getting input for only 3 times. I am not able to find solution for it.Please help with it.Thanks in advance !!

1
  • The code does not consume the newline character. If the user enters a and hits return the code will read a and then read \n. Commented Feb 4, 2014 at 15:46

3 Answers 3

5

This is because of the new-line character \n left behind by the previous scanf is read by the scanf in the next iteration. Place a space before the %c specifier to consume the \n

scanf(" %c",&c);  
       ^Notice the space
Sign up to request clarification or add additional context in comments.

Comments

0

char c is a single character variable.

In your code, your are reading time and time again characters and storing it into c, effectively overwriting it each time. If you would like to input multiple characters, consider using a character array likewise:

#include <stdio.h>

int
main (void)
{
    char c[5];
    int  counter;

    for (counter = 0; counter < 5; counter++)
      {
        printf ("Enter a character: ");
        scanf  ("%c\n", &c[i]);
      }

     printf ("The string you input is %s\n", c);

     return 0;
}

Comments

0

Suppose you enter a, b and c on the screen then it is actually taking 5 inputs
Input 1: a
Input 2: \n
Input 3: b
Input 4: \n
Input 5: \n

The newline is also taken as input

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.