Problems with scanf - c

#include <stdio.h>
int main()
{
char C, B;
int x;
printf("What comes after G\n");
scanf("%c", &C);
printf("What comes after O\n");
scanf("%c", &B);
printf("What is your age?\n");
scanf("%d", &x);
printf("You said %c comes after G, %c after T and you're %d years old? Right?", C, B, x);
return 0;
}
The problem is whenever you run the code it skips the second question "What comes after O" and then asks "What is your age?"
The only way I could avoid the program skip the 2nd question was by adding a space to the code
printf("What comes after O\n");
scanf(" %c", &B);
You can see the space between " and %c
Can you please explain this to me?

You need to eat up the white space (i.e. new line) - as per the manual page http://linux.die.net/man/3/scanf

You can use scanf to eat the single character without assigning it to anything like this::
scanf( "%[^\n]%*c", &C ) ;
%[^\n] tells the scanf to read every character that is not '\n'. That leaves the '\n' character in the input buffer, then the * (assignment suppression) will consume the a single character ('\n') but would not assign it to anything.

The reason for this problem is newline character \n leftover by the previous scanf after pressing Enter. This \n is left for the next call of scanf.
To avoid this problem you need to place a space before %c specifier in your scanf.
scanf(" %c", &C);
...
scanf(" %c", &B);
...
scanf(" %c", &X);
A space before %c is able to eat up any number of newline characters.

The problem is you are using scanf to get the character ..and a new line will be added at the end of each input from user . So the second time only the new line will be stored in the 'B' Because of the first input given by you ..
Instead of scanf , change it to getchar - your problem should get solved

Related

Why does order matter in scanf command in C programming?

#include <stdio.h>
void main() {
int i;
char x;
float y;
double z;
//line1
printf("enter an integer");
scanf("%d", &i);
//line3
printf("enter a character");
scanf("%c", &x);
printf("enter a floating point");
scanf("%f", &y);
printf("enter a double");
scanf("%lf", &z);
printf("Integer is %d \n character is %c \n floating point is %f \n double is %lf ",
i, x, y, z);
}
My question is, when I run this code it doesn't prompt the input of a character value and skips to the next command. But if I swap line 3 with 1 i.e. if I prompt for character first and then integer, then it works fine. Please help me understand this problem.
Most scanf format specifiers skip leading white-space (like newline), but %c does not (it should be able to read spaces).
That means the newline added to the input buffer from the Enter key you pressed for the previous input will be read by the %c format.
To skip leading space you need to add a space to the format string:
scanf(" %c",&x);
// ^
// Note leading space here
Use the following format string in the call of scanf for an object of the type char.
scanf(" %c",&x);
^^^
Otherwise this call (without the leading blank) will read white space characters that for example correspond to the entered key Enter.

How to prompt the user to enter an integer and a character from the keyboard in C [duplicate]

This question already has an answer here:
How to read / parse input in C? The FAQ
(1 answer)
Closed 4 years ago.
I am trying to figure out the best way to get an integer and a character from a user
Here is what I have so far:
#include <stdio.h>
int main()
{
int a;
char b;
printf("enter the first number: \n");
scanf("%d", &a);
printf("enter the second char: \n");
scanf("%c", &b);
printf("Number %d",a);
printf("Char %c",b);
return 0;
}
The output is not shown correctly. Is there any problem with this?
Your input and output statements are fine. Just replace printf("Number %d",a); with printf("Number %d\n",a); to better format the output. Also you should change your second scanf statement to scanf(" %c", &b);. This will deal with the newline character entered after the number is inputted.
After you enter the number, you pressed the Enter key. Since the scanf function works on the input stream, when you try to process the next char after reading the number, you are not reading the character you typed, but the '\n' character preceding that. (i.e. because the Enter key you pressed added a '\n' character to your input stream, before you typed your char)
You should change your second call to scanf with the following.
scanf(" %c", &b);
Notice the added space character in the formatting string. That initial space in the formatting string helps skip any whitespace in between.
Additionally, you may want to add \n at the end of the formatting strings of both printf calls you make, to have a better output formatting.
Here you need to take care of hidden character '\n' , by providing the space before the %c in scanf() function , so the "STDIN" buffer will get cleared and scanf will wait for new character in "STDIN" buffer .
modify this statement in your program : scanf("%c",&b); to scanf(" %c",&b);

scanf() function with different format specifier

Below is a program which accepts two character and prints them
#include<stdio.h>
int main()
{
char c1, c2;
printf("\n Enter characters one : ");
scanf(" %c", &c1);
printf("\n Enter character two : ");
scanf("%c", &c2);
printf("\n The the characters are %c and %c ", c1, c2);
return 0;
}
Now one output instance is :-
Enter two characters : a
The the characters are a and
The problem is that I haven't given any space between two format specifier %c
Here I pressed 'a' and then '\n' which gets stored into c1 and c2 respectively. And thus I got output which was not accepted.
I know how to correct this problem.
Now I make the same program for the integers :-
#include<stdio.h>
int main()
{
int a, b;
printf("\n Enter two numbers : ");
scanf("%d%d", &a, &b);
printf("\n The two numbers are %d and %d ", a, b);
return 0;
}
Here we will not found any problem.
I think this time we didn't encounter problem because the second input we give is '\n' or space which is not any integer and thus we get a failure in the reading from the scanf() function so the input buffer is still active and if we press the next input as integer then it gets stored into variable 'b'.
Can you tell me the reason which I thought is correct or not?
Now if it is correct then what will happen if I press again a character. Then also it should not get stored into the variable 'b' but this time 0 gets stored into variable 'b'.
So my question is that what is the reason for proper behavior of the program when I'm trying to make the same program with %d
To answer your question, let's have a look at C11 standard, chapter ยง7.21.6.2
Input white-space characters (as specified by the isspace function) are skipped, unless
the specification includes a [, c, or n specifier.
So, when you have a newline ('\n', which is indeed a white-space character) left in the input buffer,
in case of scanf("%c", &charVar);, the newline is considered as the input, so the second scanf skips asking for the input from user.
in the case of scanf("%d", &intVar); the leftover newline is skipped and it wait for the integer input to appear, so it stops and asks the user for the input.
However, FWIW, in later case, if you input a non-whitespace character and press ENTER, the char input will be considered as an input, causing a matching failure.
Related
[...] If
the input item is not a matching sequence, the execution of the directive fails: this
condition is a matching failure.
It's reading the new line as the newline is a character. Simply changing scanf("%c", &c2); to scanf(" %c", &c2); will make it work.
So in your code:
#include
int main()
{
char c1, c2;
printf("\n Enter characters one : ");
scanf(" %c", &c1);
printf("\n Enter character two : ");
scanf(" %c", &c2);
printf("\n The the characters are %c and %c ", c1, c2);
return 0;
}

In the following code I am not being able to enter value for variable 'b'

#include<stdio.h>
int main(void)
{
char a;
char b;
printf("A is ");
scanf("%c",&a);
printf("B is ");
scanf("%c",&b);
}
The reason is that when you enter first character then after pressing Enter, a newline character (\n) is also passed to the input buffer along with that character. Since scanf("%c",&a); reads a single character at a time, it left behind \n in the buffer for next call of scanf. This \n is read by your second scanf call.
Put a space before %c in scanf to consume that newline character.
scanf(" %c",&a);
Make the scanf like this
scanf(" %c", &b);
when you are after giving the value for first variable, you will give enter. Here %c will take that as input. So avoid this, make the whitespace before the control string. It will skip the whitespace character(newline, tab, space). And ask the input from the user.
You can verify that new line is taken as a input for second variable like this,
printf("%d", b); // You will get the ascii value of new line.
when you give the enter newline placed in the input buffer, then that value will taken by the scanf. So need of scanf ( getting the input) is done. so it doesn't ask the input from you.

scanf() function doesn't work? [duplicate]

This question already has answers here:
C: Multiple scanf's, when I enter in a value for one scanf it skips the second scanf [duplicate]
(7 answers)
Closed 8 years ago.
This may be a simple question, but i searched a lot and still didn't figure it out.
I compiles below snip code by gcc and run program from terminal. In correct, It allow to enter an int and a char but it doesn't. It doesn't wait to enter the char??
Anyone here can help me will be kind. thanks in advance!
#include <stdio.h>
int main()
{
char c;
int i;
// a
printf("i: ");
fflush(stdin); scanf("%d", &i);
// b
printf("c: ");
fflush(stdin); scanf("%c", &c);
return 0;
}
%d will read consecutive digits until it encounters a non-digit. %c reads one character. Probably what's happening is that you're giving it a number (several digits) followed by a new line. %c then reads in that new line. You were probably intending for the fflush(stdin); to discard anything that hadn't yet been read, but unfortunately, that's undefined behavior.
The solution is to discard all whitespace before reading the character:
scanf(" %c", &c);
Note the space at the start. That means to discard all whitespace.
You can use the getchar() to achieve what you want.
or consume the extra newline by using:-
scanf(" %c", &c);
^^^ <------------Note the space
Reason:- Your next scanf for reading the character just reads/consumes the newline and hence never waits for user input
Instead of fflush(stdin); scanf("%c", &c);
1.use scanf with extra space
scanf(" %c",&c);
or
2.use getchar() two times , first time reads '\n' which is entered after giving integer input and second time call ask you for give input as c:
getchar();
c=getchar();
would help you.
First of all, scanf works when used as directed. I think the following code does what you want. Stdout is flushed so that user is prompted to enter an integer or a character. Using %1s allows white space like \n.
int main()
{
char c[2];
int i;
printf("i: ");
fflush(stdout);
scanf("%d", &i);
printf("c: ");
fflush(stdout);
scanf("%1s", &c);
printf("\ni = %d, c = %c", i, c[0]);
return 0;
}
This code was tested/run on an Eclipse/Microsoft C compiler.
That fflush() is not guaranteed to do anything, and gcc/g++ doesn't. Not on Linux, anyway.
I thought I invented the following way to flush the rest of a line...until I saw it as an example in the ISO C spec (90 or 99...forgot which, but it's been there a long time either way...and I'll bet most readers here have seen it before.)
scanf("%*[^\n]%*c"); /* discard everything up to and including the next newline */
You can put that in your own "flush" function to save typing or pasting that all over the place.
You should still follow the suggestions to to put a space in scanf(" %c", &c);.
That will patiently wait for a non-whitespace character in case of a leading space or a double hit of the enter key.

Resources