我正在尝试 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;
}
最佳答案
首先,变量done
未初始化并且具有不确定的值
int k, done;
//...
while(done != 1){
您必须初始化它,例如
int k, done = 0;
但是最好写一个更合适的循环。也就是说,最好使用 do-while 循环来代替 while 循环。例如
int done = 0;
//...
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 != 1 );
其次,在 scanf 调用中,您应该为格式说明符指定 balnks %c
例如
if(scanf(" %c %c %c%d%f%lf", &c1, &c2, &c3, &k, &x, &y) == 6){
关于C while 循环额外迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31739783/