c - 为什么只打印输入的第二个值?

标签 c printf scanf

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int main(void)
{
    char wunit[2]; // weight unit
    char hunit[2]; // height unit

    double weight, height;

    printf("Enter the body weight: ");
    scanf("%lf%s", &weight, &wunit); // input weight and unit eg. 150lb

    printf("Enter the height: "); 
    scanf("%lf%s", &height, &hunit); // input height and unit eg. 5.65 ft

    printf("The height unit: %s\n", hunit);
    printf("The weight unit: %s", wunit);

    return 0;
}

这段代码只打印出高度单位,不打印体重单位。我该怎么做才能修复它?

最佳答案

您没有为这两个字符串留出太多空间:每个字符串只有 2 个 char。请注意,C 字符串还需要空终止字符的空间来标记字符串的结尾。

使用空终止字符,您的两个字符串每个只能正确包含一个字符。当您输入例如“lb”和“ft”,您正在使用数组范围之外的数据。将数组的大小更改为(至少)3,并查看代码是否正确打印出两个单位:

char wunit[3]; // weight unit
char hunit[3]; // height unit

您的代码适用于较大的数组。

关于c - 为什么只打印输入的第二个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12555405/

相关文章:

c - 输入非 ASCII 字符到 scanf ("%s")

c - 等待超时信号,如果收到信号则继续执行(没有与信号关联的操作)

c - 如何在控制台中获取按键事件

c - 在 C 中写入多个文件并迭代其名称

java - printf 方法不起作用

C : How to check end of input from keyboard or file while using scanf one char at a time

c - fscanf--尝试扫描int的txt文件,fscanf只读取1s

c - 在数组初始化期间从不兼容的指针类型进行初始化

c - %lf' 需要类型为 'double' 的参数,但参数 2 的类型为 'double *'

c - 返回值在 printf() 格式中不起作用