【问题标题】:When I enter an input using command line tool in Xcode, the code ignores it the first time I enter it. Why is this and is there a way to avoid it?当我在 Xcode 中使用命令行工具输入输入时,代码在我第一次输入时会忽略它。为什么会这样,有没有办法避免它?
【发布时间】:2017-07-29 02:12:11
【问题描述】:

我是 Xcode 的新手,正在使用命令行工具学习 C。通常,当我编写程序并输入输入时,代码在我第一次输入时不会执行,但是一旦第一次输入被忽略,代码就会完全按预期执行。我只是想知道这是为什么?我在编写代码时做错了什么还是这只是 Xcode 中发生的事情?

发生这种情况的代码示例(这是我上大学时必须做的事情。它读取输入“celsius=[something]”并显示一个图表,显示从摄氏度到华氏度的转换并在其上生成 cmets) :

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main()
{
    int start;
    int celsius;
    float fahrenheit;

    scanf("celsius=%d\n", &start);

    if(start<0||start>100)
    {
            printf("The value entered should be in the right range\n");
    }
    else
    {
        printf("Celsius | Fahrenheit | comment\n");
        printf("------------------------------\n");

        for(celsius=start;celsius<=100;celsius=celsius+20)
        {
            fahrenheit=celsius*(9.0/5.0)+32;
            printf("   %d   |   %.2f   |", celsius, fahrenheit);

            if(fahrenheit==32.0)
            {
                printf("  Freezing point\n");
            }
            else if(fahrenheit>=64.0&&fahrenheit<=77.0)
            {
                printf("  Room temperature\n");
            }
            else if(fahrenheit>=122.0&&fahrenheit<=176.0)
            {
                printf("  Hot bath\n");
            }
            else if(fahrenheit==212.0)
            {
                printf("  Water boils\n");
            }
            else
            {
                printf("\n");
            }
        }
    }

    return 0;
}

【问题讨论】:

    标签: c scanf format-specifiers


    【解决方案1】:

    scanf() 中提供的格式字符串需要具有完全相同的输入才能成为 匹配。你的情况

      scanf("celsius=%d\n", &start);
    

    正在创建问题,它需要一个包含

    的输入
    • celsius=字符串
    • 和整数值
    • 一个(或多个)whitespace

    和另一个newline,以终止输入。所以,最后你需要两个 ENTER 键来匹配条件。第一次按键产生一个newline,它与空格的要求相匹配,第二次,它产生另一个换行符,终止输入。

    相关,引用C11,第 7.21.6.2 章,

    由空白字符组成的指令通过读取输入执行到 第一个非空白字符(仍然未读),或者直到没有更多字符可以 被阅读。 [...]

    你需要把它减少到

     scanf("celsius=%d", &start);  //remove the trailing `\n`
    

    并检查scanf()的返回值以确保成功。

    【讨论】:

      猜你喜欢
      • 2020-08-25
      • 2020-05-28
      • 2023-02-03
      • 1970-01-01
      • 2021-04-16
      • 2023-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多