scanf() skip variable
In C, using scanf()
with the parameters, scanf("%d %*d", &a, &b)
acts differently. It enters value for just one variable not two!
Please explain this!
scanf("%d %*d", &a, &开发者_开发知识库b);
The *
basically means the specifier is ignored (integer is read, but not assigned).
Quotation from man scanf:
* Suppresses assignment. The conversion that follows occurs as usual, but no pointer is used; the result of the conversion is simply discarded.
Asterisk (*) means that the value for format will be read but won't be written into variable. scanf
doesn't expect variable pointer in its parameter list for this value. You should write:
scanf("%d %*d",&a);
http://en.wikipedia.org/wiki/Scanf#Format_string_specifications
An optional asterisk (*) right after the percent symbol denotes that the datum read by this format specifier is not to be stored in a variable.
The key here is to clear the buffer, so scanf will not think that it already has some input, and so it will not get skipped!
#include <stdio.h>
#include<stdlib.h>
void main() {
char operator;
double n1, n2;
printf("Enter two operands: ");
scanf("%lf %lf",&n1, &n2);
fflush(stdin); //do this between two scanf
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operator);
}
fflush(stdin); //this clears the scanf for new input so it does not ignore any input taking line becuase it has some charater already stored in its memory
精彩评论