Reputation: 13
In the below program when am reading input from keyboard its taking only 2 characters instead of 4 and remaining 2 characters its taking spaces by default. why is it???
program to take char input through pointers/
int c,inc,arrysize;
char *revstring;
printf("enter the size of char arry:");
scanf("%d",&arrysize);
revstring = (char *)malloc(arrysize * sizeof(*revstring));
printf("%d",sizeof(revstring));
printf("enter the array elements:");
for(inc=0;inc<arrysize;inc++)
{
scanf("%c",&revstring[inc]);
}
for(inc =0;inc<arrysize;inc++)
printf("%c",revstring[inc]);
getch();
return 0;
}
Upvotes: 1
Views: 116
Reputation: 126358
Most of the time scanf
reads formatted input. For most %
formats, scanf will first read and discard any whitespace and then parse the item specified. So with scanf("%d", ...
it will accept inputs with initial spaces (or even extra newlines!) with no problems.
One of the exceptions, however, is %c
. With %c
, scanf reads the very next character, whatever it may be. If that next character is a space or newline, that is what you get.
Depending on what exactly you want, you may be able to just use a blank space in your format string:
scanf(" %c",&revstring[inc]);
The space causes scanf
to skip any whitespace in the input, giving you the next non-whitespace character read. However, this will make it impossible to enter a string with spaces in it (the spaces will be ignored). Alternately, you could do scanf(" ");
before the loop to skip whitespace once, or scanf("%*[^\n]"); scanf("%*c");
to skip everything up to the next newline, and then skip the newline.
Upvotes: 0
Reputation: 23707
scanf
reads formatted inputs. When you tape a number, you tape the digits, and then, you press <Enter>
. So there is a remaining \n
in stdin
, which is read in the next scanf
. The same applies if you press <Enter>
between the characters.
A solution is to consume the characters in the standard input stream after each input, as follow:
#include <stdio.h>
void
clean_stdin (void)
{
int c;
while ((c = getchar ()) != '\n' && c != EOF)
;
}
Another idea is to use fgets
to get human inputs. scanf
is not suitable for such readings.
Upvotes: 3