【发布时间】:2015-07-31 06:52:12
【问题描述】:
我正在尝试对 scanf 函数进行输入验证。我已经修复了输入以忽略空格(“%c....”)。
谁能看到我做错了什么?
#include <stdio.h>
#include <stdlib.h>
int main() {
char c1, c2, c3;
int k, done = 0;
float x;
double y;
do {
printf("\n%s\n%s\n%s\n%s", "Input the following: three characters,", " an int,", " a float,", " and a double: \n");
if(scanf(" %c%c%c%d%f%lf", &c1, &c2, &c3, &k, &x, &y) == 6){
printf("\nHere is the data that you typed in: \n");
printf("%3c%3c%3c%5d%17e%17e\n\n", c1, c2, c3, k, x, y);
done = 1;
} else {
printf("Invalid input!");
}
} while (done != 0);
return EXIT_SUCCESS;
}
【问题讨论】:
-
额外迭代是什么意思?
-
在某些情况下,您也可以使用
while (true) { .. break; }构造来避免“停止变量”,例如这种情况。 -
如果您需要至少一次迭代,请使用 do...while 循环。
-
当问“有什么问题”时,你应该说为什么你认为有问题;包括错误/警告消息(如果有),以及程序是否运行;然后是你给它的输入、预期输出和实际输出。
-
抱歉大家没有进一步解释(当我问这个问题时,我在底部添加了一个解释,但由于某种原因它被删除了)。代码的目的是循环直到提供正确的输入。然而,即使我给了它正确的输入,结果也会显示出来,程序会再次循环。
标签: c while-loop iteration