【问题标题】:Problem: keep prompting user to enter code until the right they input the right values问题:不断提示用户输入代码,直到他们输入正确的值
【发布时间】:2020-05-07 12:14:39
【问题描述】:

以下代码有错误。这相对简单,但我无法弄清楚我哪里出错了。以下是部分代码:

    int target=0,nextRow;
    char nextCol;

    while(target == 0)
    {
            printf("Enter a valid target: ");
            scanf("%c%d",&nextCol,&nextRow);
            if(nextCol>= 'a' && nextCol <= 'z') /* convert to uppercase */
                    nextCol=nextCol-32;
            if(nextRow>row || nextRow<1 || nextCol<'A' || (nextCol-64)>col)
                    target=0;
            else
                    target=1;
    }

本质上,系统会提示用户输入 char 和 int,例如B4、C8 等。 Col 和 Row 是预定义的整数。如果用户输入值超出范围,则目标保持为 0。否则目标 = 1,因此循环将退出。当我运行它并继续输入无效值时,“输入有效目标”开始重复。为什么?

Image of the error

【问题讨论】:

  • 这能回答你的问题吗? scanf() leaves the new line char in the buffer
  • 尝试:scanf(" %c%d",&amp;nextCol,&amp;nextRow); 请注意%c 之前的额外空格。请参阅重复的候选人进行解释。
  • 我不认为这是问题所在,@kaylum。把问题读两遍。
  • 您的意思是“当我运行它并继续输入 有效”而不是“当我运行它并继续输入 无效值“?
  • rowcol 是如何定义的?

标签: c loops while-loop


【解决方案1】:

显然,(nextCol-64)&gt;col 的条件似乎放错了位置。

如果你输入 f.e. 'b' 作为nextCol 的输入,表达式将被评估为2 &gt; col,这似乎是错误的。

我还认为col 甚至row 的值可能是0,在这种情况下,相应的条件将始终评估为true,并且循环永远不会像看起来那样终止。

过度思考程序的逻辑!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    • 2011-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多