scanf() function with different format specifier - c

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

Related

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 is being skipped in C [duplicate]

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 5 years ago.
I tried to run the following program:
int main(){
char a;
char b;
char c;
printf("\nenter a: ");
scanf("%c", &a);
printf("\nenter b: ");
scanf("%c", &b);
printf("\nenter c: ");
scanf("%c", &c);
return 0;
}
upon running the program it prompts you to enter a value for a. once you do, you are prompted to enter a value for b, however you are not allowed to input a value because the program skips the scan and then prompts you again to input a value for c which is not skipped. I can initialize a and c, but not b. and I have no idea why. I read somewhere that using %[^\n] in the scanf, but I tried using it and I don't think I used it correctly because it still wasn't working.
this is the output (with some input examples):
enter a: 1
enter b:
enter c: 1
process returned 0 (0x0)
Instead of "%c", use " %c".
Without the space, scanf does not skip white spaces when the format specifier is %c. That is initially confusing since it will skip white spaces for other format specifiers, such as %d, %f, %s, etc.
When you press enter, that adds a character to the input queue, which is then read into b.
You can either explicitly read a character to ignore it, or you can use (for one alternative) %1s to read a single-character string (which will skip white-space, including the new-line character entered when you press enter.
'\n' becomes the input for variable b after you press enter.
so to take care of this, use getchar() which will take care of '\n'.
int main(){
char a;
char b;
char c;
printf("\nenter a: ");
scanf("%c", &a);
getchar();
printf("\nenter b: ");
scanf("%c", &b);
getchar();
printf("\nenter c: ");
scanf("%c", &c);
return 0;
}

scanf works before its execution point

I tried a simple program..function returning integer and character pointer..after i run that code i found some weird acting by scanf..I tried to print message(enter a,b:) read two integer inputs and message(enter c,d:) read two char inputs.but at run time..i found that input for the char c is read rightafter i enter the inputs for a,b..
for eg:
enter a,b: 10
20
enter c,d: g
it gets only one input(for d) and input for c is newline after 20..
for eg 2:
enter a,b: 10
20a
enter c,d: g
it gets only one input(for d) and input for c is a after 20..
why is this happening..please clarify it
int* add(int *a,int *b)
{
return (*a>*b?a:b);
}
char* charret(char *c,char *d)
{
return (*c>*d?c:d);
}
int main()
{
int a,b;
char c,d;
printf("\n\t\tFUNCTION RETURNING INTEGER POINTER\n\t");
printf("Enter the Number A and B:");
scanf("%d %d",&a,&b);
printf("\tEnter the character c :");
scanf("%c %c",&c,&d);
printf("The Biggestt Value is : %d\n\t",*add(&a,&b));
printf("\n\tThe character c= %c hi d= %c",c,d);
// scanf("%c",&d);
printf("\n\tThe Biggestt Value is : %c", *charret(&c,&d));
getch();
return 0;
}
%c will read any character, including the newline character from your previous entry. If you want to read the first non-whitespace character, add a space before %c in your format string:
scanf(" %c %c",&c,&d);
/* ^ added space */
This will cause scanf() to eat any number of whitespaces before reading the character.
For most scanf() specifiers, any leading whitespace is skipped. %c is an exception to this, because it reads a single character value, including whitespace characters. Keep in mind when you press Enter, you've sent a '\n' to the input buffer.
scanf("%d %d",&a,&b);
Reads in two numbers. The \n at the end, from pressing Enter, is left in the buffer.
scanf("%c %c",&c,&d);
Reads in two characters, the first of which will be the \n left in the buffer. One way to get around this is:
while (getch() != '\n');
This will eat everything up to an including a newline. You can put that after the scanf() lines you know will leave a newline behind.

Behavior of scanf()

why the program is not stopping at the line 4 for taking the input?
int main(int argc, char *argv[])
{
int a, b;
char c1, c2;
printf("Enter something: ");
scanf("%d",&a); // line 1
printf("Enter other something: ");
scanf("%d", &b); // line 2
printf("Enter a char: ");
scanf("%d",&c1); // line 3
printf("Enter other char: ");
scanf("%d", &c2); // line 4
printf("Done"); // line 5
system("PAUSE");
return 0;
}
i read this question from a book and in above line 4 the scanf() is not executing but why?
%d expects to read a bunch of digits from input, so that it can form an integer and store the result into the pointer you pass (which is invalid in this example, since you provided a pointer to char, but anyway, this is irrelevant here).
The problem is that if you input a character, scanf() will notice that there isn't a valid digit on input. It will read this character, push it back into the input, and return prematurely. This happens on line 3. Since the character was pushed back, line 4 will again retrieve the same character from input and see that there is no valid integer on input, so the same character is pushed back again.
The key point to keep in mind here is that scanf returns prematurely with invalid input, leaving the input stream untouched.
For example, if stdin holds the character a, scanf() on line 3 will retrieve an a from input. It sees that this cannot be a valid digit, so a "goes back" to stdin and scanf() returns. On line 4, the scanf call will do the same thing: it picks the next item from input, which is the same a, and returns prematurely. Scanning for integers won't work until you consume this character. For example, if you call getchar() after line 3, you consumed the problematic character, and scanf() on line 4 will wait for input.
scanf has issues with the newline. A quick and dirty way to solve this, is by adding a space or a \n before %c in order to bypass that...
printf("Enter a char: ");
scanf(" %c",&c1); // line 3
printf("Enter other char: ");
scanf(" %c", &c2); // line 4
printf("Enter a char: ");
scanf("%c",&c1); // line 3
printf("Enter other char: ");
scanf("%c", &c2); // line 4
change %d with %c (from decimal to character)

Odd loop does not work using %c [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.
I am leaning C programming. I have written an odd loop but doesn't work while I use %c in scanf().Here is the code:
#include<stdio.h>
void main()
{
char another='y';
int num;
while ( another =='y')
{
printf("Enter a number:\t");
scanf("%d", &num);
printf("Sqare of %d is : %d", num, num * num);
printf("\nWant to enter another number? y/n");
scanf("%c", &another);
}
}
But if I use %s in this code, for example scanf("%s", &another);, then it works fine.Why does this happen? Any idea?
The %c conversion reads the next single character from input, regardless of what it is. In this case, you've previously read a number using %d. You had to hit the enter key for that number to be read, but you haven't done anything to read the new-line from the input stream. Therefore, when you do the %c conversion, it reads that new-line from the input stream (without waiting for you to actually enter anything, since there's already input waiting to be read).
When you use %s, it skips across any leading white-space to get some character other than white-space. It treats a new-line as white-space, so it implicitly skips across that waiting new-line. Since there's (presumably) nothing else waiting to be read, it proceeds to wait for you to enter something, as you apparently desire.
If you want to use %c for the conversion, you could precede it with a space in the format string, which will also skip across any white-space in the stream.
The ENTER key is lying in the stdin stream, after you enter a number for first scanf %d. This key gets captured by the scanf %c line.
use scanf("%1s",char_array); another=char_array[0];.
use getch() instead of scanf() in this case. Because scanf() expects '\n' but you are accepting only one char at that scanf(). so '\n' given to next scanf() causing confusion.
#include<stdio.h>
void main()
{
char another='y';
int num;
while ( another =='y')
{
printf("Enter a number:\t");
scanf("%d", &num);
printf("Sqare of %d is : %d", num, num * num);
printf("\nWant to enter another number? y/n");
getchar();
scanf("%c", &another);
}
}

Resources