char Input in C by scanf - c

Help me Please.
I want to know why it happen.
This code is not give right answer:
#include < stdio.h>
int main()
{
char c,ch;
int i;
printf("Welcome buddy!\n\nPlease input first character of your name: ");
scanf("%c",&c);
printf("\nPlease input first character of your lovers name: ");
scanf("%c",&ch);
printf("\nHow many children do you want? ");
scanf("%d",&i);
printf("\n\n%c loves %c and %c want %d children",c,ch,c,i);
return 0;
}
but this code give right answer.
#include < stdio.h>
int main()
{
char c,ch;
int i;
printf("Welcome buddy!\n\nPlease input first character of your name: ");
scanf(" %c",&c);
printf("\nPlease input first character of your lovers name: ");
scanf(" %c",&ch);
printf("\nHow many children do you want? ");
scanf("%d",&i);
printf("\n\n%c loves %c and %c want %d children",c,ch,c,i);
return 0;
}
Why?
and How?
Please help me anyone who know this why it happend.

While you are giving like this, It will not ignore the white spaces.
scanf("%c",&ch);
When you are giving the input to the first scanf then you will give the enter('\n'). It is one character so it will take that as input to the second scanf. So second input will not get input from the user.
scanf(" %c",&ch);
If you give like this, then it will ignore that white space character, then it will ask for the input from the user.

The first program doesn't work properly, because the scanf function when checking for input doesn't remove automatically whitespaces when trying to parse characters.
So in the first program the value of c will be a char and the value of ch will be the '\n' (newline) char.
Using scanf("\n%c", &varname); or scanf(" %c", &varname); will parse the newline inserted while pressing enter.

The scanf function reads data from standard input stream stdin.
int scanf(const char *format, …);
The white-space characters in format, such as blanks and new-line characters, causes scanf to read, but not store, all consecutive white-space characters in the input up to the next character that is not a white-space character.
Now, when you press, by example, "a" and "return", you have two chars in the stdin stream: a and the \n char.
That is why the second call to scanf assign the \n char to ch var.

your scanf() function takes input from stdin. Now when you hit any character from keyboard and hit enter, character entered by you is scanned by scanf() but still enter is present in stdin which will be scanned by scanf() below it. To ignore white spaces you have to use scanf() with " %c".

Related

Why is the scanf() skipped?

#include <stdio.h>
int main() {
char opt;
scanf(" %c", &opt);
switch (opt) {
case 'A':
printf("Please Enter a New Name:");
char name[200];
scanf("%[^\n]s", name);
printf("Please Enter a New Code:");
char code[200];
scanf("%s", code);
printf("Please Enter the Number:");
int number;
scanf("%d", number);
printf("%s\n%s\n%d", name, code, number);
printf("\nPlease press Enter to confirm Creation");
}
}
Why is the scanf of the name skipped? the output looks like
A
Please Enter a New Name:Please Enter a New Code:
Also when switch() is removed, it works normally. Is the problem on the switch()? It does not have other cases because it is an unfinished code.
As commented by melonduofromage, your first scanf leaves the newline (\n) typed by the user after the A in the input stream. Next scanf("%[^\n]s", name) fails because the first byte from the input stream is a newline, so scanf returns immediately with a return value of 0, which you should not ignore. The program then prompts for the code and scanf skips initial white space, including the pending newline and waits for user input.
To fix this problem, add a space before the conversion specifier to skip initial white space. You should also limit the number of characters stored into the destination array: specify this number between the % and the [. Note also that the trailing s in "%[^\n]s" is useless: it is not part of the conversion specifier and scanf() will try and match it against the input stream. The correct format is scanf(" %199[^\n]", name) and the return value must be 1 for a successful conversion.
Also note that there is a missing & in scanf("%d", number): you must pass the address of the destination variable: scanf("%d", &number);
Here is a modified version:
#include <stdio.h>
int invalid_input(void) {
fprintf(stderr, "invalid or missing input\n");
return 1;
}
int main() {
char opt;
if (scanf(" %c", &opt) != 1)
return invalid_input();
switch (opt) {
case 'A':
printf("Please Enter a New Name:");
char name[200];
if (scanf(" %199[^\n]", name) != 1)
return invalid_input();
printf("Please Enter a New Code:");
char code[200];
if (scanf("%199s", code) != 1)
return invalid_input();
printf("Please Enter the Number:");
int number;
if (scanf("%d", &number) != 1)
return invalid_input();
printf("%s\n%s\n%d", name, code, number);
printf("\nPlease press Enter to confirm Creation");
//...
}
return 0;
}
When you prompt user with the first scanf here
char opt;
scanf(" %c", &opt);
When the user enters a character, say A, "A\n" is placed in the buffer, \n coming from the user hitting the return key. The scanf takes one character as requested with the " %c" format string, and leaves the \n on the buffer.
When the second scanf is executed as
printf("Please Enter a New Name:");
char name[200];
scanf("%[^\n]s", name);
the format string "%[^\n]s" requests it to read until a \n is encountered, mind you, your buffer already contains a \n as the first character, hence scanf returns without reading anything, still leaving the \n in the buffer.
When the third scanf is executed as:
printf("Please Enter a New Code:");
char code[200];
scanf("%s", code);
(Corrected after the comments of chqrlie)
The format string "%s" ignores the leading whitespaces, hence now the \n is ignored, and scanf happily waits for your input.
Notice the leading space in the format string " %c", the space is there to get scanf ignore the leading whitespace, you can implement the same logic with your second scanf. You can either ensure that all consecutive scanf ignore the \n left in the buffer, which turns out most format specifiers do, or you can ensure that no scanf leaves it to begin with with using something like "<...>%*c" to get rid of it. Though none of which are reliable and consistent methods, and as said countless times, scanf is not designed to perform such tasks like taking user input, and you should seek alternative methods.
Also, the s in "%[^\n]s" certainly doesn't do what you expect. man page of the scanf states that
An ordinary character (i.e., one other than white space or '%'). This character must exactly match the next character of input.
If it matches, scanf discards it and continues parsing according to the remaining format specifiers. If it doesn't, scanf stops there and returns. Since it is at the end of your format string, it returns either way, hiding a potential bug from you.

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);

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.

Simple C code not working

I have written a simple code to check whether a given character is present in the string entered by the user but it doesn't seem to work.
#include<stdio.h>
#include<string.h>
int main()
{
char a[20],b;
int i,p=0,n;
printf("Enter the string-");
scanf("%s",a);
printf("\nEnter the character-");
scanf("%c",&b);
n=strlen(a);
for(i=0;i<n;i++)
{
if(a[i]==b)
{
printf("\ncharacter is present in string\n");
p=1;
break;
}
}
if(p==0)
printf("\nchracter is not present in string\n");
return 0;
}
The output I get is this: http://i58.tinypic.com/2gvnedt.png
I do not see what is wrong with the code. If I replace "scanf("%s",a);" with "gets(a);" it works fine. Why?
Help is appreciated. Thanks!
Add a space character in:
scanf(" %c",&b);
^
To consume the trailing \n character that is left in stdin after the first scanf.
So a \n is left in the standard input from which scanf is reading. So when a new scanf is met it scans the old \n character.
To neutralize that effect I put a space character in scanf i.e. I am telling it to expect to read a \n or space or \t and then to read a %c.

Why 2nd scanf doesn't work in my program?

scanf("%d %c",&size,&chara); works but separate scanf for character input does not work. I show these inside the code. Why is that?
void squareCustomFill(int size, char chara);
int main(void) {
int size,i,k;
char chara;
printf("Enter size of square: "); //This works
scanf("%d %c",&size,&chara);
//printf("Enter fill character: "); BUT WHY DOES NOT THIS WORK??
//scanf("%c",&chara);
squareCustomFill(size,chara);
return 0;
}
void squareCustomFill(int size, char chara){
int i,k;
for (k=1;k<=size;k++){
for(i=1;i<=size;i++)
printf("%c",chara);
printf("\n");
}
}
Scanf did not consume the \n character that stayed in the buffer from the first scanf call.
So the second scanf call did.
You have to clear the stdin before reading again or just get rid of the newline.
The second call should be
scanf(" %c",&chara);
^ this space this will read whitespace charaters( what newline also is) until it finds a single char
Yes I believe Armin is correct. scanf will read in whitespace (spacebar, newline, etc.). When you're inputting values if you click the space bar or enter right after the first scanf, the second scanf will read in that value (space, newline, etc.). So you fixed that with scanf("%d %c",&size,&chara) because there is a space between %d and %c. If you want them separate just do what Armin suggested: scanf(" %c",&chara).
Throw a getchar() in between them and slurp up that extraneous newline.

Resources