c - 当我在 Xcode 中使用命令行工具输入内容时,代码会在我第一次输入时忽略它。为什么会这样,有没有办法避免呢?

标签 c scanf format-specifiers

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

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

#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;
}

最佳答案

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

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

正在制造问题,它需要一个由以下内容组成的输入

  • celsius= 字符串
  • 和整数值
  • 一个(或多个)空格

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

相关,引用C11,章节§7.21.6.2,

A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read. [...]

你需要把它减少到

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

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

关于c - 当我在 Xcode 中使用命令行工具输入内容时,代码会在我第一次输入时忽略它。为什么会这样,有没有办法避免呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42672534/

相关文章:

c - 删除数组中的最后一个整数而不使其变为零

c - 适当的 malloc 错误修复

c - 如何使用 gcc 显示预处理的宏(仅由用户定义)?

c - 为什么 printf 中缺少参数不会产生错误

c - %g printf 说明符到底是什么意思?

c - "Arrays = Pointers"*令人震惊*。许多年后 : "Actually, they don' t"*mind blown again*

c - 带有 C 字符串的 scanf 和 strcmp

c - 在 C 中使用 scanf() 从 stdin 读取输入

c - 理解 scanf 语法

c++ - 格式化 IO 函数 (*printf/*scanf) 中的转换说明符 %i 和 %d 有什么区别