-1
#include <stdio.h>
int main ()
{
char c[10];
int k=0;
printf("please enter the element value in character\n");
for(k=0;k<10;k++)
{     
scanf("%c",&c[k]);
}
for(k=0;k<10;k++)
{
printf("Value in char is %c\n",c[k]);
}
return 0;
}

//problem is that i can only initialize value of 5 char not 10. My IDE is code::blocks with GNU GCC COMPILER .

Maddy
  • 17
  • 4

2 Answers2

0

You can use scanf("%c%*c"); to read the newline after your character. The %*c matches a single character, but the asterisk indicates that the character will not be stored anywhere. This has the effect of consuming the newline character generated by the enter key so that the next time you call scanf() you are starting with an empty input buffer.

cleblanc
  • 3,678
  • 1
  • 13
  • 16
  • thanks,but can u explain ? – Maddy Mar 13 '17 at 18:27
  • Each `scanf("%c")` call reads just on character and leaves the newline character stuck in the stdin buffer. You need to consume that character before calling `scanf(...)` a second time or it will return the newline character '\n', – cleblanc Mar 13 '17 at 18:30
0

When you press enter from your keyboard, the program reads the char you have just entered (e.g 'a') along with a new-line character("\n") from pressing the enter button. You must handle this in your code by writing your scanf the following way: scanf(" %c" , &c[k]) . There must be a whitespace before the %c. This tells the compiler to ignore all whitespace characters.