【问题标题】:Printing an int value obtained from user打印从用户获得的 int 值
【发布时间】:2015-05-31 21:16:55
【问题描述】:

问题出在age 部分,编译器没有给我任何错误,但是当我运行它时,它会为 int age 打印一个random number

printf("Enter your name:");
scanf(" %s",&name1);
int age;
printf("\n\nHow old are you?");
scanf(" %d",&age);
char gender;
printf("\n\nEnter your gender[Male/Female]:");
scanf(" %s",&gender);
char confirmation;
printf("Confirmation: Your name is %s , you are %d years old , and you are a %s.\n\nAnswer[Y/N]:",&name1,age,&gender);

【问题讨论】:

  • 您在输入的年龄前面是否加了空格?
  • 还有,返回值是多少?
  • 我敢打赌,如果你初始化int age=42;输出不会像你想象的那么随机。
  • @WeatherVane 用户应该输入年龄而不是我-_-
  • &%s 一起使用是错误的

标签: c printing int scanf


【解决方案1】:

这是你的问题。

char gender;
scanf(" %s",&gender);

genderchar。也就是说,它只有一个 1 字节字符的内存。但是您将其用作字符串。 name1 可能也有同样的问题,因为您也在使用 &,但不能确定,因为您没有显示。

将其更改为:

char gender[8] // Enough to fit "Female" and terminating NULL
scanf("%7s", gender);

额外说明:scanf 用于防止缓冲区安全有点尴尬。可以考虑用sscanf 代替fgets

【讨论】:

    【解决方案2】:

    还有动态分配,您现在不必指定要使用的存储量。将长度修饰符%m与字符串类型修饰符s一起使用:

    #include <stdio.h>
    #include <stdlib.h>
    
    
    int main(int argc, char *argv[])
    {
        char *name = NULL
        char *gender = NULL;
        int age;
    
        printf("Enter your name: ");
        scanf("%ms", &name);
    
        printf("\nHow old are you? ");
        scanf("%d", &age);
    
        printf("\nEnter gender: ");
        scanf(" %ms", &gender);
    
        printf("\n%s %d %s\n", name, age, gender);
    
        free(name);   //  free the memory
        free(gender); //   
    
        return 0;
    }
    

    在最后几行中,您会注意到对free 的多次调用。这是因为您有责任释放scanf 分配的内存。

    正如@Matt McNabb 所指出的,如果您使用的是不符合 posix 的系统,这将不起作用。您可以使用a 代替m,同时在第一行包含#define _GNU_SOURCE

    【讨论】:

    • 好资料!为了完整性,可能应该检查scanf 调用的返回值,以便free 只有在scanf 成功且没有错误的情况下才能完成。或者将指针初始化为 NULL,以便 free 始终获得有效输入(NULLfree 正确处理)。
    • 好点,我想就没有安全检查发表评论。
    • %ms 是 POSIX 扩展,它不在 ISO C 中
    • @MattMcNabb 我记下了这一点
    猜你喜欢
    • 1970-01-01
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多