[英]Why isn't my integer printing out properly in C
我只是想写一些需要一个月和日期的东西,然后打印出来。 我写了以下代码:
int main(void){
char month[] = {};
int day;
printf("Please enter the month and day of you date. i.e January 01\n\n");
scanf("%s,%d", month, &day);
printf("Month is %s and the day is %d\n", month, day);
return 0;
}
当我输入像 12 月 22 日这样的日期时,我得到以下打印输出:月份是 12 月,日期是 1。日期值打印为 1。为什么我的日期 integer 没有更新,而是停留在 1?
本声明
char month[] = {};
在 C 和 C++ 中无效。
至少你应该写例如
char month[10];
在提示中,输入日期的格式不带逗号
printf("Please enter the month and day of you date. i.e January 01\n\n");
但是在scanf的调用中
scanf("%s,%d", month, &day);
现在有一个逗号。
该程序可以通过以下方式查找示例
#include <stdio.h>
int main( void )
{
char month[10];
unsigned int day;
printf( "Please enter the month and day of you date. i.e January 01\n\n" );
if (scanf( "%9s %u", month, &day ) == 2)
{
printf( "Month is %s and the day is %02u\n", month, day );
}
}
程序 output 可能看起来像
Please enter the month and day of you date. i.e January 01
December 22
Month is December and the day is 22
如果你想在输入字符串中包含一个逗号,那么程序可以像下面这样
#included <stdio.h>
int main( void )
{
char month[10];
unsigned int day;
printf( "Please enter the month and day of you date. i.e January, 01\n\n" );
if (scanf( "%9[^,], %u", month, &day ) == 2)
{
printf( "Month is %s and the day is %02u\n", month, day );
}
}
程序 output 可能看起来像
Please enter the month and day of you date. i.e January, 01
January, 01
Month is January and the day is 01
另一种方法是使用 function fgets
而不是scanf
例如
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
int main( void )
{
char date[14];
printf( "Please enter the month and day of you date. i.e January, 01\n\n" );
int success = fgets( date, sizeof( date ), stdin ) != NULL;
if (success)
{
const char *p = strchr( date, ',' );
if (success = p != NULL)
{
char *endptr;
unsigned int day = strtoul( p + 1, &endptr, 10 );
if ( success = endptr != p + 1 )
{
printf( "Month is %.*s and the day is %02u\n",
( int )( p - date ), date, day );
}
}
}
}
程序 output 可能看起来像
Please enter the month and day of you date. i.e January, 01
January, 01
Month is January and the day is 01
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.