This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
C skipping one command of a function? [duplicate]
(2 answers)
Closed 6 years ago.
I've been given the pretty simple task of writing a program that will take two characters and then print the letters inbetween them using a for() loop.
Here's my code:
#include <stdio.h>
int main() {
char a, b;
printf("\nEnter the first character: ");
scanf("%c", &a);
printf("\nEnter the second character: ");
scanf("%c", &b);
for(char i = a; i <= b; i++) {
printf("%c ", i);
}
return 0;
}
When I run it, I am prompted to enter the first character correctly but when I press enter it only runs the next printf() and then terminates.
No errors or warnings or anything on compilation. Another similar question I found that was apparently solved does not work for me either.
Thanks in advance.
You have to consume the \n in stdin left by first scanf.
Fastest fix
scanf(" %c", &b);
The space before %c tells to scanf to ignore all whitespaces before to read the char.
If I read your code correctly, by pressing enter, you would enter the second character, which would most probably (depending on the environment) start with a numeric value of 13, which would be smaller than any letter, so the loop's body is executed only once.
Related
This question already has answers here:
The program doesn't stop on scanf("%c", &ch) line, why? [duplicate]
(2 answers)
Closed 1 year ago.
I'm struggling on a question proving scanf() and getchar() can both retrieve a character from the input.
However, when I try to put them inside the same program, only the first function is running properly. The latter is discarded completely.
#include <stdio.h>
char letter;
int main()
{
printf("I'm waiting for a character: ");
letter = getchar();
printf("\nNo, %c is not the character I want.\nTry again.\n\n",letter);
printf("I'm waiting for a different character: ");
scanf("%c",&letter);
printf("Yes, %c is the one I'm thinking of!\n",letter);
return(0);
}
output
I have tried switching the places of those two functions but it is of no use.
Can someone help me find the issue and provide a way to fix this? The only requirement is that the program takes input twice, once by the getchar() function and once via scanf()
The second read attempt just reads whitespace (the end of line character, since you pressed enter after the first letter). Simply replace it with this:
scanf(" %c", &letter);
The space before % will tell scanf to read the next non-whitespace character.
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);
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 is part of a university lab and the TA tells me there is an error but I haven't a clue. When I run it it asks me for the first char but then runs through the program and doesn't ask me at the second scanf.
#include <stdio.h>
int main(void) {
char sen, ben;
printf("Type in a character: ");
scanf("%c", &sen);
printf("The key just accepted is %d", sen);
printf("\nType in another character: ");
scanf("%c", &ben);
printf("The key just accepted is %d", ben);
}
Actually this is C not C++. Save it as file.c.
Try this:
#include <stdio.h>
int main(void) {
char sen, ben;
printf("Type in a character: ");
sen = getchar();
printf("The key just accepted is %d", sen);
printf("\nType in another character: ");
getchar();
ben = getchar();
printf("The key just accepted is %d", ben);
}
Explanation: when you enter the first character and press enter it takes enter's ASCII code as the second.
I suggest not to use scanf. But it works both ways if you put a getchar to "take" the enter.
Adding a space before %c in the second scanf will solve the issue.
This is done because scanf does not consume the \n character after you enter the first character and leaves it in the stdin.As the Enter key(\n) is also a character,it gets consumed by the next scanf call.The space before the %c will discard all blanks like spaces.
When you are scanning a character(%c) using scanf,add a space before %c as it would help reduce confusion and help you. Therefore, in both the scanfs , you can add the space.
When you pressed your key and then hit enter, you typed in two keys. The first was the desired key ,a for example, and the second was the key <enter> typically written as \n. So, your second scanf captures the result \n.
Since printing out the \n character doesn't result in something that is easy to see on the screen, it will appear like your program is just skipping the second scanf and printing out only the fixed parts of the printf without a easily viewable value.
One way to get around this problem is to consume all the key strokes just before the key you want to capture. This is done by accepting more input after the character up until you see a newline character \n. Once you see that character, then you do your next read.
// flush extra input up the to carriage return
char flush = 0;
while (flush != '\n') {
scanf("%c", &flush);
}
// now read my desired input
scanf("%c", &ben);
that's because nobody accepts '\n'. call scanf like this scanf("%c%*c", &sen). %*c means you want to omit one character, which is '\n'.
btw, void main() is allowed. main function is not the real entry point of executable, so it's ok to do that. but it seems not everybody likes it.
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.
This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 3 years ago.
It is a statement given in K&R that printf() and putchar() can be interleaved. If it true then why is the following code not giving the required output:-
#include"stdio.h"
void main()
{
char c,d;
printf("Enter the first character\n");
scanf("%c",&c);
printf("%c\n",c);
printf("Enter the second character\n");
d=getchar();
putchar(d);
printf("\n");
}
Whenever I am executing this program, the output is as follows:-
Enter the first character
a
a
Enter the second character
This is the output. This is also happening if I replace printf() by putchar() and scanf() by getchar(). Why is this happpening?
The first scanf leaves in the input buffer the \n resulting from the Return press, so your second getchar() will acquire this \n instead of acquiring another character from the user.
If you want to skip that newline character, you can either instruct the scanf to "eat" it:
scanf("%c\n",&c);
or "eat it" directly with a call to getchar():
scanf("%c",&c);
getchar();
(notice that these are not exactly equivalent, since the second snippet will eat whatever character happens to be in the buffer, while the first one will remove it only if it's a \n)
You can correct your code like this:
#include <stdio.h>
int main() {
char c, d;
printf("Enter the first character\n");
scanf("%c\n", &c); // Ask scanf to read newline and skip
printf("%c\n", c);
printf("Enter the second character\n");
d = getchar();
putchar(d);
printf("\n");
return 0;
}
You are getting two a's because you type one in which is echoed to the console and then you print it out.
flush the stdin before using getchar()..
In turbo, use fflush()..
In gcc, use __fpurge(stdin)..(this is available in <stdio_ext.h> header)..
Flushing the standard input before scanning anything will solve your issue..