Thursday, October 31, 2013

%c format specifier limitation.


The limitation of %c format specification is that, it receives the white space characters also. The white space character includes tab, space, enter etc. This limitation of %c format specifier can be rectified by %1s format specifier. The %1s format specifier can be used to receive a non white space character.
Look at the following program:

#include <stdio.h>
#include <conio.h>
void main()
{
          char ch;
clrscr();
printf(“Enter any character:”);
scanf(“%c”,,&ch);
printf(“”\nInputted character is=%c”,ch);
getch();
}

Run the program and press Enter. You will get the following output.
Output:
#----------------------------------------------------------------#
Enter any character:<Enter>
inputted character is=
#----------------------------------------------------------------#

Fixing the limitation of %c format specification by using %1s format specifier.
#include <stdio.h>
#include <conio.h>
void main()
{
          char ch;
clrscr();
printf(“Enter any character:”);
scanf(“%1s”,,&ch);
printf(“”\nInputted character is=%c”,ch);
getch();
}

Now, run the program and press Enter or try pressing any other white space character. The program does nothing until you provide the character from the console.
#----------------------------------------------------------------#
Enter any character:<Enter>
<Enter>
<space><Enter>
y
inputted character is=y

#----------------------------------------------------------------#

No comments:

Post a Comment