This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 2 years ago.
I'm still learning the basics of C right now and I wanted to build a simple 'enter y to loop the program' that I've seen in a lot of console programs and wrote the following code to test it out. When I do execute it however, it does work as intended once after which the program just exits. It would help me a lot if anyone told me what I'm doing wrong here :
int main()
{
char l;
do
{
printf("Loop successful.\n");
fflush(stdin); //I heard this has to be used because scanf keeps the enter key in buffer or something like that
scanf_s("%c", &l);
} while (l == 'y');
}
I also get a "Missing integer argument to 'scanf(_s)' that corresponds to conversion specifier '2'" warning and I don't seem to understand what I'm being warned against.
fflush(stdin); //I heard this has to be used because scanf keeps the enter key in
That's wrong, fflushing stdin is undefined behaviour, what you need to do is consume the newlines lefted by the previous scan, just switch from
scanf_s("%c", &l);
to
scanf_s(" %c", &l); // Notice the space before %
Related
This question already has answers here:
C programming - Loop until user inputs number scanf
(4 answers)
Closed 4 years ago.
edit1:
Sorry, I am in an intro to programming class... I read the two links, but don't fully understand them...
I tried to to add
if (scanf_s("%d", &input) == 0) {
fflush(stdin);
continue;
}
but that didn't seem to do anything. I understand that scanf is in an error state, so it will refuse to run, and that I need to clear a buffer of the bad input from user.
so basically, I am looking for a beginner's solution, for someone who just learned about loops, input/output, and basic error check.
~~~~~~~~~
I am new to C and have a small question. I want to read a list of integers from the console. It works fine if the user does indeed input integers, but if it types something like "acdb", or "0.5", I just get the program printing "enter a number: " infinitely, as if it's running the loop but scanf_s is broken and so it just skips itself.
Thanks for your help.
int input = 1;
while (input != 0) {
printf("enter a number: \n");
scanf_s("%d", &input);
/* rest of code omitted */
}
scanf_s returns the number of variables in the variable argument list that were successfully filled with data.
In your case you want that to be 1 therefore.
If you do encounter invalid input then it's your job to clear that, otherwise it remains on the input stream. For more on that see How to clear input buffer in C?
This question already has answers here:
fflush(stdin) function does not work
(3 answers)
fflush() is not working in Linux
(9 answers)
Why fflush(stdin) does not remove buffer (stdin) [duplicate]
(2 answers)
How to clear input buffer in C?
(18 answers)
Closed 5 years ago.
This is the code which I'm trying to run on my Mac. In this the statement after fflush doesn't work. After fflush the compiler should stop and wait for the user input but it doesn't.
Can anyone tell me why this is happening or is there any other way to do it?
int main()
{
int pos,neg,zero,num;
char ans = 'y';
pos=neg=zero=0;
while(ans == 'y' || ans=='Y')
{
printf("\nEnter a number : ");
scanf("%d",&num);
if(num==0)
zero++;
if(num>0)
pos++;
if(num<0)
neg++;
fflush(stdin);
printf("\nDo you want to continue?\n\n");
scanf("%c",&ans);
}
printf("You entered %d positive numbers\n",pos);
printf("You entered %d negative numbers\n",neg);
printf("You entered %d zeros \n",zero);
return 0;
}
From standard 7.21.5.2
If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes
any unwritten data for that stream to be delivered to the host
environment to be written to the file; otherwise, the behavior is
undefined.
You were having undefined behavior in your code. More clearly, fflush won't work. The most common way to do it would be something as shown below:
int c;
while ((c = getchar()) != '\n' && c != EOF){}
Another solution would be to use (much easier for you but not robust)
scanf(" %c",&ans);
^^
This will make sure all white space is being consumed. This will solve one of the problem that may arise, but not all. (The others arise due to use of scanf and wrong input).
Side note
Also another way to get rid of this problem altogether would be to use fgets or similar to read one line and then use strtol or strtod to get the desired input parsed from the inputted line. scanf is extremely useful for formatted input. The scenario which you will have - it is better to use fgets, there are too many cases with scanf that you have to deal with otherwise.
For wrong input you need to flush the standard input so that you don't have to deal with them again in the next scanf. If you use fgets then you will get the input line from the stdin and then if you can parse it and the input is correct - you go on processing it, else you discard the whole line and wait for the next fgets call.
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:
Simple C scanf does not work? [duplicate]
(5 answers)
Closed 7 years ago.
I have a question, We were asked by our teacher to write a rock paper scissors program using the if else statement
my problem is
if i code it like this
char a, b;
clrscr();
printf("\n Enter player 1 value");
scanf("%c", &a);
printf("\n Enter Player 2 value:);
scanf("%c", &b);
my problem is when i code it like this after entering the 1st value it ignores the second one and just goes on the if statements
and i found a solution which is putting space on %c on the second scanf which looks like this (found a similar program)
scanf(" %c", &b);
and it works but now i don't know why ??
can anyone explain to me why it was being ignored and why putting a space solves that problem ?? it will gladly help
thanks in advance
by adding a space you exclude the whitespaces created by the previous scanf.
scanf() stops as soon it finds a whitespace so if the string start with a whitespace you get nothing.
use scanf("%[^\n]", &variable) to get everything (space included) or even better
scanf("%30[^\n]", &variable) to get everything with a size limit on the input (in this case 30).
There is also another function that lets you read from a stream:
fgets(&variable, sizeof variable, stdin); check the doc out here(http://www.cplusplus.com/reference/cstdio/fgets/)
This question already has answers here:
How to do scanf for single char in C [duplicate]
(11 answers)
Closed 8 years ago.
I have problem with this code:
printf("Select your math: \n'+'addition \n'-'subtraction \n'*'multiplication \n'/' division \n");
char do_math;
scanf("%c", &do_math);
printf("Type 1 st number: ");
Problem is, that program doesn't wait until I type "do_math" but it displays "Type 1 st number: " right after first printf. Any ideas?
The only way your compiler will miscompile that is if you deliberately defined scanf() as a do-nothing macro. Don't blame your compiler!
There is probably a previous scanf() call in the program that left a carriage return in the input buffer. You can confirm that hypothesis by printing the value of do_math.
Try scanf(" %c", &do_math); (with a space before %c) to discard such whitespace.
(It's also a good idea to pay attention to the return value from scanf().)