简体   繁体   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;
}

I'm running this through ideone.com and it shows success, then standard input is empty, then in stdout it prints all my print statements with no numbers 我正在ideone.com上运行它,它显示成功,然后标准输入为空,然后在stdout中它显示我所有不带数字的打印语句

This is because ideone is not interactive. 这是因为ideone 不是交互式的。 Unlike running your program from the command line, ideone requires you to provide all the input upfront in the "input" tab: 与从命令行运行程序不同,ideone要求您在“输入”选项卡中预先提供所有输入:

伊迪奥

You need to enter all your data before running your program. 您需要运行程序之前输入所有数据。

PS Once you do, notice how you have undefined behavior because you pass values, rather than pointers, to scanf . PS完成后,请注意您有未定义的行为,因为您将值而不是指针传递给scanf The best way to address this on ideone is to pick "C99 strict" option when compiling your C code. 在ideone上解决此问题的最佳方法是在编译C代码时选择“ C99 strict”选项。 This would break your compile with the following warning: 使用以下警告将破坏您的编译:

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

  scanf("%f", base); 

scanf requires a pointer to your data type, you should pass the address of your variables using & : scanf需要一个指向您的数据类型的指针,您应该使用&传递变量的地址:

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

To add, some error checking might be useful, something like: 另外,一些错误检查可能很有用,例如:

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