【问题标题】:C program terminates before accepting scanf() inputC 程序在接受 scanf() 输入之前终止
【发布时间】:2019-10-01 06:22:20
【问题描述】:

虽然我知道这个程序的布局很奇怪,但我认为我的程序在涉及scanf() 行时遇到了问题。由于某种原因,在输入metricConversion() 函数后。打印了scanf() 行,但程序在给出输入之前退出并终止......我不明白为什么会发生这种情况......

#include <stdio.h>

char inputtedChar;
int inputtedInt;

int metricConversion(){
    scanf("Press K for conversion from Kelvin to Celsius %c", &inputtedChar);

    if(inputtedChar == 'K'){
        //do Something
    } else { return 0; }
}

int main() {
    printf("Press 0 to enter conversion function!");
    scanf("%d", &inputtedInt);

    if (inputtedInt == 0) {
        metricConversion();
    }
}

更重要的是,有人可以解释为什么scanf() 会这样工作吗?最好的选择是什么,所以我不会再遇到这种情况了?

【问题讨论】:

  • 您确定打印了scanf() 行吗?

标签: c input scanf


【解决方案1】:

scanf("Press K for conversion from Kelvin to Celsius %c", &amp;inputtedChar); 更改为:

printf("Press K for conversion from Kelvin to Celsius ");
fflush(stdout);
scanf(" %c", &inputtedChar);
/*     ^                    */
/*   this space             */

有 2 个问题。使用printf 进行提示。并且您需要在scanf 中使用空格来忽略%c%[…](扫描集)或%n 转换之前的空格。使用fflush 将确保在等待输入之前将提示打印在屏幕上。

建议在main 函数中在scanf 之前使用fflush,除非您想用'\n' 终止打印字符串。


scanf("Press K for conversion from Kelvin to Celsius %c", &amp;inputtedChar); 是什么意思?

这不会打印任何东西。这意味着程序需要精确的输入 Press K for conversion from Kelvin to Celsius &lt;SOME_CHAR&gt; 并在输入中读取 &lt;SOME_CHAR&gt;。有关更多详细信息,您需要了解正则表达式。

【讨论】:

  • 有 2 个问题。 三个 问题 - 从未检查来自 scanf() 的返回值以确保实际从控制台读取了某些内容.
  • 非常感谢!那么,为什么空间会产生如此大的差异呢?作为一个新的 C 程序员,我什至不知道从哪里开始寻找解决这样一个小问题......
  • @CosmicCat Space makes a difference when you are reading a char with %c 因为空格也是char。当您指定一个空格时,您要求scanf 跳过每个空白字符(空格、制表符、换行符等)并读取第一个非空白字符。没有空格,您要求的第一个字符可能是也可能不是空格。要解决此类问题,您可以阅读用于 ex 的功能规范。 scanf 在这种情况下来自手册页或好书并解决一些玩具问题。
猜你喜欢
  • 1970-01-01
  • 2016-01-30
  • 1970-01-01
  • 1970-01-01
  • 2020-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-11
相关资源
最近更新 更多