【问题标题】:why does scanf() input variable not output as the value it contains? instead it prints the memory location为什么 scanf() 输入变量不输出为它包含的值?而是打印内存位置
【发布时间】:2022-06-10 19:46:33
【问题描述】:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int valueEntered ,x;
   
    scanf("enter the value:%d",&valueEntered);

    x = valueEntered;

    printf("the value entered is:%d\n", x);

    return 0;
}

【问题讨论】:

  • 请编辑您的问题以包括输入、预期输出和您看到的当前输出。你也没有问任何问题(标题不是问题)
  • printf("输入值:"); scanf("%d",&valueEntered);
  • 而且它没有打印“内存位置”。它只是打印了一些垃圾值,因为valueEntered 没有初始化,scanf 也失败了,正如上面第二条评论中所暗示的那样。
  • 在尝试使用scanf 操作的结果之前,您应该始终检查scanf 的返回值,以验证它是否成功。有关详细信息,请参阅本指南:A beginners' guide away from scanf()
  • scanf 操作将失败,除非用户自己输入"enter the value:" 后跟一个数字。但是,您可能不希望用户必须输入该字符串,而是希望您的程序打印该字符串。因此,您应该改写printf( "Enter a value: " ); scanf( "%d", &amp;valueEntered );

标签: c printf scanf format-string


【解决方案1】:

拆分scanf的这个电话

scanf("enter the value:%d",&valueEntered);

拨打printfscanf

printf( "enter the value " );
scanf("%d",&valueEntered);

否则scanf的调用会尝试在输入流中查找字符串"enter the value:"

一般来说你应该检查scanf的调用是否成功。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-17
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    • 1970-01-01
    • 2021-10-08
    • 1970-01-01
    相关资源
    最近更新 更多