Pelles C forum

C language => Beginner questions => Topic started by: Starter on August 20, 2015, 09:34:58 AM

Title: scanf characters problem
Post by: Starter on August 20, 2015, 09:34:58 AM
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...
Title: Re: scanf characters problem
Post by: TimoVJL on August 20, 2015, 03:12:58 PM
Try
Code: [Select]
...
scanf(" %c", &k);
printf("<%c> %d\n", k, k);
...
and think again format string.
Title: Re: scanf characters problem
Post by: Starter on August 31, 2015, 05:33:54 AM
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?
 
Title: Re: scanf characters problem
Post by: Starter on August 31, 2015, 05:36:52 AM
"%c"

No problem with Turbo C
Title: Re: scanf characters problem
Post by: TimoVJL on August 31, 2015, 07:37:17 AM
Read least this (http://stackoverflow.com/questions/7166197/why-does-a-space-in-my-scanf-statement-make-a-difference)
Title: Re: scanf characters problem
Post by: frankie on August 31, 2015, 10:13:07 AM
For scanf() even the <Enter> pressed after the character is a valid input. That's why you got:
Code: [Select]
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.
Title: Re: scanf characters problem
Post by: Starter on September 03, 2015, 10:33:13 AM
Thank you so much for all reply.
I thought It should be the same as "%i" and "%f" for number.