【问题标题】:Reading a string into integers, then printing the integers将字符串读入整数,然后打印整数
【发布时间】:2021-09-13 17:20:27
【问题描述】:
#include <stdio.h>
#include <stdio.h>
#include <string.h>

int main(){
    char* InputUserDate;
    int yyyy;
    int mm;
    int dd;
    printf("Your Date of Birth yyyy-mm-dd:");
    scanf("%s",&InputUserDate);
    sscanf(InputUserDate, "%d-%d-%d", &yyyy, &mm, &dd);
    printf("year: %d, month: %d, day: %d\n", yyyy, mm, dd);
}

这是我的代码。我想在InputUserDate 中收集用户的输入。我使用sscanf 将字符串转换为三个整数,并将它们存储在三个变量中。但是,没有输出。

我的输入:2000-04-01

我希望输出是这样的:

Year:2000

Month:04

Day:01

【问题讨论】:

  • 没有为InputUserDate 分配空间,因此您正在调用未定义的行为,试图将用户输入写入它所指向的位置。试试char InputUserDate[64];
  • 在读取用户字符串之前需要内存。 char* InputUserDate 不为字符串提供任何内存。它只是声明了一个指针,该指针可用于指向包含字符串的内存。
  • 并更改scanf("%s",&amp;InputUserDate); --> scanf("%s",InputUserDate);,您不需要&amp;scanf 期望char* 用于"%s" 格式说明符。这在启用警告时会很明显:​​godbolt.org/z/541Mx41K1

标签: c io


【解决方案1】:

char* InputUserDate; 只是一个未初始化的指针——它不指向任何有效的内存。您必须为要写入的字符串分配内存。一种方法是定义一个数组:例如,char input[32];

"%s" 需要一个char *,指向要写入的有效内存,而&amp;InputUserDate 的类型是char **

当用作函数参数时,数组衰减为指向第一个元素的指针 -- char input[32] 在传递给 scanf 时变为 char *

"%s" 不应该在没有指定目标缓冲区的最大字段宽度的情况下使用 - 这应该比缓冲区的大小小一,以便为 NUL 终止字节(@ 987654332@) C 中所有有效的字符串 都需要。

scanfsscanf 都可能失败,或部分匹配您指定的转化总数。在任何一种情况下,参数指向的值都可能是不确定的。您必须检查函数的返回值是否与成功所需的转换说明符的数量相匹配,以便程序的其余部分对有效数据进行操作。

#include <stdio.h>
#include <string.h>

int main(void) {
    char input[32];  
    int yyyy, mm, dd;

    printf("Your Date of Birth yyyy-mm-dd:");

    if (scanf("%31s", input) == 1 &&
            sscanf(input, "%d-%d-%d", &yyyy, &mm, &dd) == 3) {
        printf("year: %d, month: %d, day: %d\n", yyyy, mm, dd);
    }
}

强烈考虑使用fgets 而不是scanf 来读取输入行,因为这样可以更好地控制。

【讨论】:

    猜你喜欢
    • 2018-11-25
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    相关资源
    最近更新 更多