【问题标题】:How to convert format long value 20010203 to string 2001-02-03?如何将格式长值 20010203 转换为字符串 2001-02-03?
【发布时间】:2023-04-04 04:24:01
【问题描述】:

我有可变长。示例:

long date = 20010203;

我需要通过 cout 以这种格式 2001-02-03 打印值。示例:

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

我需要将值 long 20010203 转换为带有“-”的字符串格式以进行打印。怎么做? 我只能使用这些库:

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

【问题讨论】:

  • 作业什么时候交?查看cstring 提供的标准 C 字符串函数,周围有一百万个教程。
  • cplusplus.com/reference/cstring/?kw=cstring cstring 没有将整数转换为字符串的函数。什么意思?

标签: c++ string date type-conversion


【解决方案1】:

最基本的方法是:

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

【讨论】:

  • 但之前的月份和日期不为零。 02 06 等
  • 然后呢?你只需要做一个简单的条件检查你的数字是否低于 9,如果是,则在它之前显示一个零......
【解决方案2】:

朴素的方法,划分和截断

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

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

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

编辑,我很笨

【讨论】:

    【解决方案3】:

    你可以这样做:

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

    【讨论】:

      猜你喜欢
      • 2013-04-05
      • 1970-01-01
      • 1970-01-01
      • 2020-07-23
      • 2018-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-11
      相关资源
      最近更新 更多