scanf characters problem

Started by Starter, August 20, 2015, 09:34:58 AM

Previous topic - Next topic

Starter

I want to print 5 characters by loop but it doesn't work.
Could anyone help me please!
or it is bug of pelles c?

#include<stdio.h>

int main(void)
{
int i;
char k;
   for(i=1;i<=5;i++)
   {
       printf("Enter Character: ");
      scanf("%c",&k);
      printf("<%c> \n",k);
   }

return 0;
}

output
Enter character: a
<a>
Enter character: <                       <== I didn't key
>
Enter character: b
<b>
Enter character: <                       <== I didn't key
>
Enter character: c
<c>
Press any key to continue...

TimoVJL

Try...
scanf(" %c", &k);
printf("<%c> %d\n", k, k);
...
and think again format string.
May the source be with you

Starter

Thank you for your reply.
But I need only one character.(no space)
I used "%s" instead of "%c" It work!
But how about "%c" problem?

Starter


TimoVJL

May the source be with you

frankie

For scanf() even the <Enter> pressed after the character is a valid input. That's why you got:
Enter character: a
<a>
Enter character: <                       <== This is the CR of <ENTER>
>


Quote"%c" No problem with Turbo C
It is TurboC that has a problem! The behavior above is common to all current compilers and compliant with standards. TurboC is preAnsi and not compliant.

The solution proposed by Timo is from the stndard. A space in  format string will consume any whitespace in between (includind '\n') if present any. Following Timo suggestion scanf() will remove any space or '\n' before the char you want read.
"It is better to be hated for what you are than to be loved for what you are not." - Andre Gide

Starter

Thank you so much for all reply.
I thought It should be the same as "%i" and "%f" for number.