【问题标题】:Scan function only read 4 digit of the input扫描功能只读取输入的 4 位
【发布时间】:2015-02-23 21:38:33
【问题描述】:

我正在编写一个程序来获取今天的数据并打印出明天的数据。但是,当我尝试获取今天的日期时,scanf 函数似乎只读取了前四位数字。输出是错误的。

例如:如果我输入 08 19 1995,它读取 0 为今天.月,8 为今天.日,19 为今天.年

代码是:

//Write a function to print out tomorrow's date

#include <stdio.h>
#include <stdbool.h>

struct date
{
    int month;
    int day;
    int year;
};

int main(void)
{
    struct date today, tomorrow;
    int numberofdays(struct date d);

    //get today's date
    printf("Please enter today's date (mm dd yyyy):");
    scanf("%i%i%i",&today.month, &today.day, &today.year);

    //sytax to find the tomorrow's date
    if(today.day == numberofdays( today))
    {
        if(today.month==12)  //end of the year
        {
            tomorrow.day=1;
            tomorrow.month=1;
            tomorrow.year=today.year+1;
        }
        else    //end of the month
        {
            tomorrow.day=1;
            tomorrow.month=today.month+1;
            tomorrow.year=today.year%100;
        }
    }
    else
    {
        tomorrow.day=today.day+1;
        tomorrow.month=today.month;
        tomorrow.year=today.year;    
    }
    printf("\nTomorrow's date is:");
    printf("%i/%i/%i\n",tomorrow.month,tomorrow.day,tomorrow.year);
    return 0;
}

// A function to find how many days in a month, considering the leap year
int numberofdays( struct date d)
{
    int days;
    bool isleapyear( struct date d);
    int day[12]=
    {31,28,31,30,31,30,31,31,30,31,30,31};
    if(d.month==2&&isleapyear(d)==true)
    {
        days=29;
        return days;
    }
    else 
    {
        days = day[d.month-1];
        return days;
    }
}

//a fuction to test whether it is a leapyear or not
bool isleapyear( struct date d)
{
    bool flag;
    if(d.year%100==0)
    {
        if(d.year%400==0)
        {
            flag=true;
            return flag;
        }
        else
        {
            flag=false;
            return flag;
        }
    }
    else
    {
        if(d.year%4==0)
        {
            flag=true;
            return flag;
        }
        else
        {
            flag=false;
            return flag;
        }
    }
}

【问题讨论】:

  • 使用"%i %i %i"作为格式字符串。
  • 我试过了,还是不行。
  • 你是对的使用"%d %d %d"%i 可以读取八进制数,所以 08 被读取为两个数字,08 不是一个好的八进制数,所以它被读取为 0 然后 8。
  • 不测试 scanf() 的返回值是在寻求惊喜。
  • @Jean-Baptiste Yunès 在读取 3 个整数时:"%i%i%i""%i %i %i" 相同。在格式中添加空格对阅读 3 int 没有影响。同样:"%d%d%d" 将像 "%d %d %d" 一样扫描。

标签: c scanf


【解决方案1】:

您必须使用%d %d %d 以十进制格式扫描输入,因为当您提供%i 格式说明符时,如果您在数字前面指定0,它会将来自标准输入的输入视为八进制格式.注意!。

编辑:我建议你阅读scanf().here的文档

此链接中关于scanf() 如何与i 转换说明符一起使用的重要内容是:

匹配一个可选的有符号整数; next 指针必须是指向 int 的指针。如果整数以 0x 或 0X 开头,则以 16 为基数读取,如果以 0 开头,则以 8 为基数读取,否则以 10 为基数读取。仅使用对应于基础的字符。

【讨论】:

  • %i 不将输入视为八进制。 %o 将输入视为八进制。 %i 将输入视为十进制、八进制或十六进制,具体取决于前导 char
  • 我没有指示 %i 是否应将输入视为十进制或八进制的前导字符。怎么用?
  • @silencefox 你可以使用%d
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
  • 1970-01-01
相关资源
最近更新 更多