首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >程序演示结构没有收到正确的输入值。

程序演示结构没有收到正确的输入值。
EN

Stack Overflow用户
提问于 2014-06-10 02:49:26
回答 2查看 117关注 0票数 1

这个简单的程序通过确定明天的日期来演示结构的使用。它要求输入今天的日期:

代码语言:javascript
复制
#include    <stdlib.h>
#include    <stdio.h>

int main ( int argc, char *argv[] )
{

    struct date {
        int month;
        int day;
        int year;
    };  /* ----------  end of struct date  ---------- */

    struct date today, tomorrow;

    const int   daysPerMonth[12] = { 31, 28, 31, 30, 31, 30,
                         31, 31, 30, 31, 30, 31 };

    printf ( "Enter today's date (mm dd yyyy): \n" );
    scanf ( "%i%i%i", &today.month, &today.day, &today.year );

    if ( today.day != daysPerMonth[today.month - 1] ) {
        tomorrow.day = today.day + 1;
        tomorrow.month = today.month;
        tomorrow.year = today.year;
    }
    else if ( today.month == 12 ) {         /* end of year */
        tomorrow.day = 1;
        tomorrow.month = 1;
        tomorrow.year = today.year + 1;
    }
    else {                                  /* end of month */
        tomorrow.day = 1;
        tomorrow.month = today.month + 1;
        tomorrow.year = today.year;
    }

    printf ( "Tomorrow's date is %i/%i/%.2i.\n", tomorrow.month,
          tomorrow.day, tomorrow.year % 100 );

    return EXIT_SUCCESS;
}       /* ----------  end of function main  ---------- */

在运行的时候,我得到的是:

输入今天的日期(mm dd yyyy): 06 09 2014 明天是09年6月1日。

但是,当我运行gdb并输出输入值时:

代码语言:javascript
复制
(gdb) p today.month

$1 = 6

(gdb) p today.day

$2 = 0

(gdb) p today.year

$3 = 9 

我很困惑。为什么输入得到这样不正确的值?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-06-10 02:54:46

哈哈。用于%iscanf说明符意味着以一系列整数格式读取,这与为C整数文本指定的格式类似。

当您键入一个前导0时,它意味着下面是八进制数字。因为9不是有效的八进制数字,所以只读取0值。9留给下面的%i,因此读取的三个数字是6092014保留在输入流中。

要输入基本10,将%i更改为%d,那么您的程序就可以工作了。

票数 3
EN

Stack Overflow用户

发布于 2014-06-10 02:54:59

您将输入读入为scanf ( "%i%i%i", &today.month, &today.day, &today.year );

由于您在输入中以0前缀,所以它们被视为八进制,从而导致结果。

您应该使用scanf("%d%d%d", ...);代替。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24132082

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档