【发布时间】: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",&InputUserDate);-->scanf("%s",InputUserDate);,您不需要&,scanf期望char*用于"%s"格式说明符。这在启用警告时会很明显:godbolt.org/z/541Mx41K1