繁体   English   中英

scanf()不提示在stdin中输入

[英]scanf() doesn't prompt input in stdin

#include <stdio.h>

int main(void) {
    float base, height, hyp;

    printf("input base of triangle:\n");
    scanf("%f", base);

    printf("input height of triangle:\n");
    scanf("%f", height);

    printf("input hypotenuse of triangle:\n");
    scanf("%f", hyp);

    float perimeter = base + height + hyp;

    printf("the perimeter of your triangle is: %f\n", perimeter);



    return 0;
}

我正在ideone.com上运行它,它显示成功,然后标准输入为空,然后在stdout中它显示我所有不带数字的打印语句

这是因为ideone 不是交互式的。 与从命令行运行程序不同,ideone要求您在“输入”选项卡中预先提供所有输入:

伊迪奥

您需要运行程序之前输入所有数据。

PS完成后,请注意您有未定义的行为,因为您将值而不是指针传递给scanf 在ideone上解决此问题的最佳方法是在编译C代码时选择“ C99 strict”选项。 使用以下警告将破坏您的编译:

prog.c:7:11:错误:格式'%f'期望类型为'float *',但是参数2的类型为'double'[-Werror = format =]

  scanf("%f", base); 

scanf需要一个指向您的数据类型的指针,您应该使用&传递变量的地址:

scanf("%f", &base);
scanf("%f", &height);
scanf("%f", &hyp);

另外,一些错误检查可能很有用,例如:

if(scanf("%f", &base) != 1) //number of items scanned is expected to be 1
  //process error..
//etc

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM