For a start, lets think about what you want fflush(stdin);
to do. fflush
only operates on streams that have been written to; it causes any unwritten (cached) data to be fully written, and it makes no sense in the context of stdin
.
This is a common mistake. When you tell scanf
to read an integer (or a floating point, whatever) it'll stop reading when it no longer sees anything numeric. This means you'll probably have a leftover '\n'
on the stream, at least. The user might have also entered other (erroneous) input that you want to discard.
The idea of discarding user input is horrible! You should think about accepting input in a different form (e.g. using argv
in int main(int argc, char **argv)
) to make their uncomfortable life a little more comfortable.
If you can't do that (or you don't want to), you can use one of the following pieces of code to discard up to (and including) the next '\n'
:
void fdiscardline(FILE *f) {
int c;
do {
c = fgetc(f);
} while (c != EOF && c != '\n');
}
void fdiscardline(FILE *f) {
fscanf(f, "%*[^\n]");
fgetc(f);
}
You should use this after your input, not before. Also, you need to think about what i
should be. Should it be zero when more input can be read (e.g. while (i==0)
), or zero when input wasn't read correctly? You need to be consistent because that's your loops terminal condition. For example:
#include <stdio.h>
int main() {
double A1;
int n1, loopchck, i=0;
while (i==0) {
printf("Enter a real number and inerger (A n): ");
loopchck=scanf_s(" %lf %d", &A1, &n1);
fdiscardline(stdin);
if (loopchck == 2) {
i = 0;
}
else {
i = 1;
}
}
return 0;
}