【发布时间】:2011-11-28 06:48:33
【问题描述】:
在 C 中,将 scanf() 与参数一起使用,scanf("%d %*d", &a, &b) 的行为不同。它只输入一个变量而不是两个变量的值!
请解释一下!
scanf("%d %*d", &a, &b);
【问题讨论】:
在 C 中,将 scanf() 与参数一起使用,scanf("%d %*d", &a, &b) 的行为不同。它只输入一个变量而不是两个变量的值!
请解释一下!
scanf("%d %*d", &a, &b);
【问题讨论】:
* 基本上意味着说明符被忽略(读取整数,但未分配)。
引用man scanf:
* Suppresses assignment. The conversion that follows occurs as usual, but no pointer is used; the result of the conversion is simply discarded.
【讨论】:
星号 (*) 表示将读取格式的值,但不会将其写入变量。 scanf 不希望其参数列表中的变量指针用于该值。你应该写:
scanf("%d %*d",&a);
【讨论】:
fscanf 读取的字符之后的所有字符?即忽略所有内容直到行尾?我已经找了很久了。
scanf 只从stdin(和文件中的fscanf)读取满足格式字符串所需的字符。如果您在变量中得到不正确的值,这意味着您得到与格式匹配的错误。检查返回值。如果它没有帮助,我想你需要用例子发布一个适当的问题。
http://en.wikipedia.org/wiki/Scanf#Format_string_specifications
百分号后面的可选星号 (*) 表示此格式说明符读取的数据不存储在变量中。
【讨论】:
这里的关键是清空缓冲区,这样scanf就不会认为它已经有一些输入,所以不会被跳过!
#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); //这会清除新输入的scanf,因此它不会忽略任何输入,因为它有 一些字符已经存储在它的内存中
【讨论】: