为什么我的整数在C中不能正确打印出来

ewm0tg9j  于 2023-01-20  发布在  其他
关注(0)|答案(1)|浏览(163)

我试着写一些需要一个月和日期的东西,然后把它打印出来。我写了下面的代码:

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;
}

当我输入像December 22这样的日期时,会打印出以下内容:月份是十二月,日期是1。日期值打印为1。为什么我的日期整数不更新,而是停留在1?

vulvrdjw

vulvrdjw1#

本声明

char month[] = {};

在C和C++中无效。
至少你应该写个例子

char month[10];

在提示符中,显示的输入日期格式不带逗号

printf("Please enter the month and day of you date. i.e January 01\n\n");

但在斯坎夫的召唤下

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 );
    }
}

程序输出可能如下所示

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 );
    }
}

程序输出可能如下所示

Please enter the month and day of you date. i.e January, 01

January, 01
Month is January and the day is 01

另一种方法是使用函数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 );
            }
        }
    }
}

程序输出可能如下所示

Please enter the month and day of you date. i.e January, 01

January, 01
Month is January and the day is 01

相关问题