【问题标题】:loop executes more than needed [duplicate]循环执行超过需要[重复]
【发布时间】:2013-10-26 11:36:08
【问题描述】:

我有以下代码:

#include<stdio.h>
#include "commonf.h" //So, this is the way you include from a directory?
void main(){
    println("Welcome to Number Guesser v 0.1 ");
    println("Think of a number between 0 and 100 (and please, make it an integer!)");
    println("Legend: Y=Yes B=Bigger than that S= Smaller than that");
    int guessed=0;
    float curnum=100.0;
    char cursign='?';
    while(cursign!='y'){
        if(cursign=='?' || cursign=='s'){
            curnum=curnum/2;
        }
        else if(cursign=='b'){
            curnum=curnum+curnum/2;
        }
        else{
            printf("You are wrong. Stop it. %c .  TEESST",cursign);
        }
        char askstring[4096];
        sprintf(askstring,"%s%f%s","Is your number ",curnum," ? (y/b/s)");
        println(askstring);
        scanf("%c",&cursign); //Scanf has to expect a new line for some reason.
    }
}

(我都贴了,因为我是菜鸟)

如果代码如下所示,则每次用户输入时循环将执行两次,一次使用 cursign= 对用户输入的任何内容,一次使用它等于 \n。

如果我将 scanf 行更改为

scanf("%c\n",&cursign);

它要求第一个输入两次,然后作为一个魅力。有什么问题,我该怎么办?

【问题讨论】:

标签: c scanf


【解决方案1】:

将此scanf("%c\n",&amp;cursign); 更改为此scanf(" %c",&amp;cursign);。这会吃掉尾随的换行符。

同样按照标准main 应该返回一个int(即使这不是你的问题的原因)。根据 C 标准 main 应该是 int main(void)int main(int argc, char* argv[])

当您输入像y 这样的字符并按ENTER 键时,一个字符(您输入的)和一个字符(即回车键-换行符)将被放置在输入缓冲区中。第一个字符被scanf 消耗,但换行符仍保留在输入缓冲区中,所以下次您在其中输入3 个字符newlinechar + 'y' + newlinechar 时会发生什么情况。这让scanf 的行为很有趣。

这是来自 Grijesh 的一个很棒的链接 - C Printf and Scanf Reference

【讨论】:

  • 修复了它。我能解释一下为什么空格应该在 %c 之前,而不是在它之后吗?
  • @user2534511 是的,因为in format string a sequence of white-space characters (space, tab, newline, etc.; see isspace(3)). This directive matches any amount of white space, including none, in the input. 实际上你的循环不是无限运行或多次运行!!!
  • @user2534511 我用你的问题标记了一个链接,在那里阅读问答。
  • @Acme 根据 C 标准 main 应该是 int main(void)int main(int argc, char* argv[])
  • @GrijeshChauhan - 感谢您完成那部分:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-13
  • 2019-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-28
相关资源
最近更新 更多