This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 6 months ago.
#include <stdio.h>
int main() {
char v1,v2,v3;
printf("enter: ");
scanf("%c",&v1);
printf("enter: ");
scanf("%c",&v2);
printf("enter: ");
scanf("%c",&v3);
}
this is my sample code and I expect an output like:
enter: a
enter: b
enter: c
but I'm getting output like:
enter: a
enter: enter:
2nd and 3rd print statements are getting executed simultaneously.
The problem is that you're reading characters, so if what you enter is actually aEnterbEntercEnter, that is actually SIX characters, and what you read will be the first 3 (the a, the Enter, and the b)
What you can do is use a space in the scanf format to skip whitespace. If you use scanf(" %c", &v1); then any whitespace (such as Enter) will be skipped, which will cause your result to be what you expect. However, if someone enters something like spaceEnter, the program will seem to hang, waiting for non-whitespace to be entered
The problem lies in buffering. Read this question, which was already mentioned in the comments.
TL,DR: Use scanf(" %c", &v); to read chars, since it ignores all whitespace from the buffer, as well as the trailing newline.
Hello what I would recommend is using a library that allows you to use a function called get_char.
I wrote a program using this function that does what you wanted yours to do.
#include <stdio.h>
#include <string.h>
#include <cs50.h>
int main(void)
{
char v1 = get_char("enter: ");
char v2 = get_char("enter: ");
char v3 = get_char("enter: ");
}
So the program stores 3 char values as they are entered one after another, without all executing at once. I don't know if this is the type of answer that you are looking for or if it will help you, but I figured I would put this out there. If its not really what your looking for let me know!
This is what the terminal looks like btw.:
$ make help
$ ./help
enter: a
enter: b
enter: c
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 answers here:
fgets instructions gets skipped.Why?
(3 answers)
Closed 6 years ago.
I have written a simple program in C which is as follows:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int length;
printf("Enter the length of the string:\t");
scanf("%d",&length);
char str1[10];
printf("Enter string:\t");
gets(str1);
printf("%s",str1);
return 0;
}
When I execute it - I get an output as:
Enter the length of the string: 5
Enter string:
Process returned 0 (0x0) execution time : 1.740 s
Press any key to continue.
I don't know why it doesn't ask for the string input and simply quits the program.
When you type '5’ followed by the enter key, you are sending two chars to the program - '5' and newline. So your first scanf gets the '5' and the second gets the newline, which it converts to the number zero.
See How to read a line from the console in C?
When you enter 5 and press enter which is "\n" then "\n" remains in stream and gets assigned to str1. You need to take that "\n" out of the input stream for which many choices are there. You can figure that out. :) Perhaps later I will edit this answer to let you know.
Edit 1:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int length;
char c;
printf("Enter the length of the string:\t");
scanf("%d%c",&length, &c);
char str1[10];
printf("Enter string:\t");
gets(str1);
printf("%s",str1);
return 0;
}
This is incorrect way of doing it but your code will at least start working. You can also simply call getc(stdin) which is slightly better. The scanf regex specified in the other answers where it has been marked as duplicate will also work but is ugly and unnecessarily complicated.
I have not tested this and it may not work.
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.
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:
Scanf skips every other while loop in C
(10 answers)
Store data in array from input [duplicate]
(2 answers)
Closed 8 years ago.
I have the following code:
#include<stdio.h>
#include "commonf.h" //So, this is the way you include from a directory?
void main(){
println("Welcome to Number Guesser v 0.1 ");
println("Think of a number between 0 and 100 (and please, make it an integer!)");
println("Legend: Y=Yes B=Bigger than that S= Smaller than that");
int guessed=0;
float curnum=100.0;
char cursign='?';
while(cursign!='y'){
if(cursign=='?' || cursign=='s'){
curnum=curnum/2;
}
else if(cursign=='b'){
curnum=curnum+curnum/2;
}
else{
printf("You are wrong. Stop it. %c . TEESST",cursign);
}
char askstring[4096];
sprintf(askstring,"%s%f%s","Is your number ",curnum," ? (y/b/s)");
println(askstring);
scanf("%c",&cursign); //Scanf has to expect a new line for some reason.
}
}
(I pasted all of it, since I am a c noob)
If the code looks like this, the loop will execute twice per user input, once with cursign= to whatever the user entered, and once with it equal to \n.
If I change the scanf line to
scanf("%c\n",&cursign);
It asks for the first input twice, then works as a charm. What's the problem, and what should I do?
Change this scanf("%c\n",&cursign); to this scanf(" %c",&cursign);. This will eat up the trailing newline character.
Also as per standard main should return an int (even though this is not the reason for your problem). According to C standards main should be int main(void) or int main(int argc, char* argv[])
When you enter a character like y and hit the ENTER key, a character (which you entered) and a character (which is the enter keystroke - the newline character) gets placed in the input buffer. The first character gets consumed by the scanf but the newline remains in the input buffer so what happens is that the next time you enter something there 3 characters newlinechar + 'y' + newlinechar. So that makes scanf behave funny.
This is a great link from Grijesh - C Printf and Scanf Reference