C++ 如何将格式长值20010203转换为字符串2001-02-03?

C++ 如何将格式长值20010203转换为字符串2001-02-03?,c++,string,date,type-conversion,C++,String,Date,Type Conversion,我已经很久了。例如: long date = 20010203; 我需要以这种格式打印cout值2001-02-03。示例: cout << "Today is " << "2001-02-03" << endl; cout简单的方法,分割和截断 20010203/10000000=2,现在您有了第一个数字 从20010203中减去(10000000*2)得到0010203 冲洗并重复,直到您拥有所有必要的数字 编辑,我是哑巴最基本的方法是: long y

我已经很久了。例如:

long date = 20010203;
我需要以这种格式打印cout值2001-02-03。示例:

cout << "Today is " << "2001-02-03" << endl;

cout简单的方法,分割和截断

20010203/10000000=2,现在您有了第一个数字

从20010203中减去(10000000*2)得到0010203

冲洗并重复,直到您拥有所有必要的数字


编辑,我是哑巴

最基本的方法是:

long year = date / 10000;
long month = (date - (year * 10000)) / 100;
long day = (date - (year * 10000) - (month * 100));

std::cout << "Today is " << year << "-" << (month < 10 ? "0" : "") << month << "-" << (day < 10 ? "0" : "") << day << std::endl;;
long year=date/10000;
长月=(日期-(年*10000))/100;
长日=(日期-(年*10000)-(月*100));

std::cout您可以这样做:

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>

int main ()
{
    long date=20010203;
    char arr[9];
    sprintf(arr, "%ld", date);//converts long to string
    std::cout << "Today is ";
    for(int i=0; i<9; i++)
    {
        if(i==4 || i==6) std::cout << '-';
        std::cout << arr[i];
    }
    return 0;
}
#包括
#包括
#包括
#包括
int main()
{
长日期=20010203;
char-arr[9];
sprintf(arr,“%ld”,date);//将long转换为字符串

std::cout作业什么时候到期?看看通过
cstring
提供的标准C字符串函数,大约有一百万个教程。cstring没有从整数转换为字符串的函数。你是什么意思?但是月和日在.02 06之前都没有零,等等?你只需要做一个简单的条件检查,看看你的数字是否是推断的或9,并在其前面显示一个零,如果是。。。
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>

int main ()
{
    long date=20010203;
    char arr[9];
    sprintf(arr, "%ld", date);//converts long to string
    std::cout << "Today is ";
    for(int i=0; i<9; i++)
    {
        if(i==4 || i==6) std::cout << '-';
        std::cout << arr[i];
    }
    return 0;
}