C while 循环额外迭代

标签 c while-loop iteration

我正在尝试 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/

相关文章:

c - 在 Windows 的 C/C++ 中打开 com 端口时将 HANDLE 作为参数传递

在 Mac OS X 上使用 SWIG 编译 Ruby 库

python - 如何在 while 循环中将程序的控制权传回调用函数

php - 如何检查所有行是否符合 PHP 中的条件

java - 简单的 Java 查询 - 从整数获取结果

c# - 提高 Excel 文件创建的性能

c - C语言中的#line关键字

c - 设置参数

javascript - 迭代表格的所有子元素并重置背景颜色

go - 创建迭代 JSON 目录树 - Golang