NO

Author Topic: scanf characters problem  (Read 3915 times)

Starter

  • Guest
scanf characters problem
« 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...

Offline TimoVJL

  • Global Moderator
  • Member
  • *****
  • Posts: 2091
Re: scanf characters problem
« Reply #1 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.
May the source be with you

Starter

  • Guest
Re: scanf characters problem
« Reply #2 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?
 

Starter

  • Guest
Re: scanf characters problem
« Reply #3 on: August 31, 2015, 05:36:52 AM »
"%c"

No problem with Turbo C

Offline TimoVJL

  • Global Moderator
  • Member
  • *****
  • Posts: 2091
Re: scanf characters problem
« Reply #4 on: August 31, 2015, 07:37:17 AM »
Read least this
May the source be with you

Offline frankie

  • Global Moderator
  • Member
  • *****
  • Posts: 2096
Re: scanf characters problem
« Reply #5 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.
It is better to be hated for what you are than to be loved for what you are not. - Andre Gide

Starter

  • Guest
Re: scanf characters problem
« Reply #6 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.