the following code as expected should accept two char values from user. but it just accepts one value of ch1 and then prints "hello".
#include<stdio.h>
int main()
{
char ch1, ch2;
printf("Enter a char: ");
scanf("%c",&ch1);
printf("Enter second char: ");
scanf("%c",&ch2);
printf("Hello");
return 0;
}
it is not accepting the second value for ch2..what can be the possible reason?
As far as i think, it should accept 2 characters.
It just accepts only one char because the the first call to scanf() left a newline in the input stream.
You can ignore it with:
scanf(" %c",&ch2); // note the leading space.
This will ensure the newline from the previous input will be ignored. A white-space in the format string tells scanf() to ignore any number of white-space characters. You might also want to check the return value of scanf() calls in case it failed.
From scanf():
. A sequence of white-space characters (space, tab, newline,
etc.; see isspace(3)). This directive matches any amount of
white space, including none, in the input.
Related
I was fiddling with C and happen to wrote code below. When I input a string with spaces, program receives all of the input but outputs them as if they were inputted as single words at different times. I thought scanf stopped when first whitespace character is encounterd and ignored the rest. But that seems, is not the case.
I included the output when I enter "inputWithNoSpaces" and "input with spaces", below.
I tried to look into stdin. It receives all the input. But I could not figure out what scanf was doing. I would like to learn what is happening.
Code:
#include <stdio.h>
int main()
{
int i=0;
char word[64]="";
while(1)
{
printf("enter string:");
scanf("%s",word);
i++;
printf("%d:%s\n\n",i,word);
}
return 0;
}
Output:
enter string:inputWithNoSpaces
1:inputWithNoSpaces
enter string:input with spaces
2:input
enter string:3:with
enter string:4:spaces
enter string:
In scanf(), "%s" means "skip whitespace characters then read a sequence of non-whitespace characters". So when you give it the input input with spaces it will return "input", "with" and "spaces" in three sequential calls. That is the expected behavior. For more information read the manual page.
input with spaces
^^^^^ First scanf("%s", s) reads this
^ Second scanf("%s", s) skips over this whitespace
^^^^ Second scanf("%s", s) reads this
^ Third scanf("%s", s) skips over this whitespace
^^^^^^ Third scanf("%s", s) reads this
#include<stdio.h>
int main()
{
int a,b;
printf("enter two numbers ");
scanf("%d \n%d",&a,&b);
printf("%d %d",a,b);
return 0;
}
when I give inputs like 3 and 5 , then the issue is that even if I give inputs without any newline character in between them then also the scanf function scans the input value , but in the formal string I have stated that the next input should be scanned after a newline character so how can the next input be scanned just after some few whitespaces .
White-space in the scanf format string tells scanf (and family) to read and ignore white-space in the input. It doesn't matter what kind of white-space character you use in the format: Space, newlines and tabs are all the same.
However, you don't actually need it for all formats. most scanf formats automatically reads and ignore leading white-space, including the "%d" format.
The " \n" in the "%d \n%d" format string will "eat" all whitespace characters as defined by isspace, including newlines.
To force reading the integers off separate lines, use this instead:
if(scanf("%d%*[^\n]\n%d",&a,&b) != 2) return EXIT_ERROR;
I am trying to add some characters at the end of a string using the following code. I am not getting the desired output.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int l,i;
char a[30];
printf("Enter \n");
scanf("%s",a);
l=strlen(a);
for(i=l;i<(29-l);i++)
{
scanf("%c",&a[i]);
a[i+1]='\0';
printf("\n%s",a);
}
return 0;
}
I guess, the problem is with whitespace. After you enter the first string, there is still a newline \n in the input buffer. When you then read one character with scanf, you get the newline and not the character you entered.
You can skip the whitespace, when you prefix the format string with a space
scanf(" %c",&a[i]);
Now it will append the character entered at the end of the string.
Update:
From scanf
The format string consists of a sequence of directives which describe how to process the sequence of input characters.
...
• A sequence of white-space characters (space, tab, newline, etc.; see isspace(3)). This directive matches any amount of white space, including none, in the input.
This means, when you insert a space in the format string, it will skip all white-space in the input.
This will happen automatically with other input directives like %s or %d. But %c takes the next character, even if it is a white-space char. Therefore, if you want to skip white-space in this case, you must tell scanf by inserting a space in the format string.
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;
}
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.
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.
On Windows,
char c;
int i;
scanf("%d", &i);
scanf("%c", &c);
The computer skips to retrieve character from console because '\n' is remaining on buffer.
However, I found out that the code below works well.
char str[10];
int i;
scanf("%d", &i);
scanf("%s", str);
Just like the case above, '\n' is remaining on buffer but why scanf successfully gets the string from console this time?
From the gcc man page (I don't have Windows handy):
%c: matches a fixed number of characters, always. The maximum field width says how
many characters to read; if you don't specify the maximum, the default is 1. It also does not skip over initial whitespace characters.
%s: matches a string of non-whitespace characters. It skips and discards initial
whitespace, but stops when it encounters more whitespace after having read something.
[ This clause should explain the behaviour you are seeing. ]
Having trouble understanding the question, but scanf ignores all whitespace characters. n is a whitespace character. If you want to detect when user presses enter you should use fgets.
fgets(str, 10, stdin);