sscanf转换为长整数

xGe*_*Gen 0 c

任何人都可以解释以下行的输出:

sprintf(tempStr,"%s%2s%s",year_str,month_str,day_str);    
count=sscanf(tempStr,"%ld%s",&tempout,other);
Run Code Online (Sandbox Code Playgroud)

它使用日,月和年值创建数字日期.

但是,它如何将数值转换为长整数

对于例如:你能告诉我,如果,2016,0208,那么这将是输出值tempout.

这里是输入的方式:

    char date_str[20];

    char day_str[2];
    char month_str[2];
    char year_str[2];

    time_t now;
    struct tm* current_time;

    /* get current time */
    now = time(0); 

    /* convert time to tm structure */
    current_time = localtime(&now);

    /* format day string */
    sprintf(day_str,"%02d",current_time->tm_mday);

    /* format month string */
    sprintf(month_str,"%02d",current_time->tm_mon + 1);

    /* format year string */
    sprintf(year_str,"%d",current_time->tm_year);

    /* assemble date string */
    sprintf(date_str,"%s%2s%s",year_str,month_str,day_str);
Run Code Online (Sandbox Code Playgroud)

我运行它时的输出(使用http://cpp.sh/),我得到的是:

1160208

而我认为它应该是:

20160208.

在其他一些情况下,下面有一行,116如果年份是2016:

sprintf(year_str,"%02d",options.year - 1900);

这里date_strtempStr上面提到的,因此,输入是:1160208

Ahm*_*tar 5

该格式说明%ld是隐式类型转换的数值long int,反之,%dint独自一人.

编辑:

我现在运行你的代码,使用其中提到的变量的以下数据类型:

#include<stdio.h>
#include<string.h>
int main()
{
 char tempStr[100];
 char year_str[5];
 char month_str[3];
 char day_str[3];
 long int tempout;
 char other[100];
 int count;

 strcpy(year_str, "2016");
 strcpy(month_str ,"02");
 strcpy(day_str ,"08");

 sprintf(tempStr,"%s%2s%s",year_str,month_str,day_str);
 count=sscanf(tempStr,"%ld%s",&tempout,other);

 printf("tempStr: %s\ntempout: %ld\n", tempStr,tempout);
}
Run Code Online (Sandbox Code Playgroud)

然后我才明白你的顾虑是什么,输出显示:

tempStr:20160208
tempout:20160208

显然,我们可以看到这里存在的问题是否sprintf存在sscanf.

格式说明%s%2s%s你已经给sprintf你想办法串联的三根弦,year_str,month_strday_str分别,没有任何字符("/",空间" - ")在他们之间.该2%2s仅仅意味着两个空格只有在有可能的填充.

这意味着,当sscanf将试图读取long inttempout会读20160208成一个数字做正确它是什么意思做.

因此,你必须一个字符添加诸如space -/,,一切都将正常工作:

sprintf(tempStr,"%s %2s %s", year_str,month_str,day_str);
Run Code Online (Sandbox Code Playgroud)

新产品现在是:

tempStr:2016 02 08
tempout:2016

EDIT2:

如果您查看localtime()Man Page,您会看到其成员的范围struct tm是:

tm_mday

每月的日期,范围为1到31.

tm_mon

自1月以来的月数,范围为0到11.

tm_year

自1900年以来的年数.

这也解释了加1sprintf(month_str,"%02d",current_time->tm_mon + 1);如此相似,1900应添加到current_time->tm_year正确的输出:

sprintf(year_str,"%d",current_time->tm_year+1900);
Run Code Online (Sandbox Code Playgroud)