【问题标题】:Using CTime & asctime to assign time to a string or vector string使用 CTime 和 asctime 将时间分配给字符串或向量字符串
【发布时间】:2011-05-11 04:09:38
【问题描述】:

我想使用 asctime 将时间分配给字符串。

time_t rawtime;
time ( &rawtime );
vector<string> TTime;
TTime.resize(10);
TTime = asctime(localtime ( &rawtime ));

我知道 asctime 正在返回一个指向字符串的指针。我是否必须创建自己的字符串并为其分配 asctime 的返回值,还是有更简单的方法?

【问题讨论】:

    标签: c++ string ctime


    【解决方案1】:

    你可以直接从char *构造一个字符串:

    string str = asctime(localtime ( &rawtime ));
    

    这没有意义:

    TTime = asctime(localtime ( &rawtime ));
    

    您不能将单个字符串分配给字符串向量。你可以做的是:

    TTime[0] = asctime(localtime ( &rawtime ));
    

    【讨论】:

      【解决方案2】:

      看起来你需要的是一个简单的字符串,

      std::string TTime(asctime(localtime(&rawtime)));
      

      【讨论】:

      • 这确实有效。我不知道为什么,但我认为每个字符串只能包含一个单词,并且以空格结尾。
      【解决方案3】:

      函数 asctime() 返回 char* 并且 std::string 可以从 char* 构造

      std::string time(asctime(localtime(&rawtime)));

      std::string 时间; 时间 = asctime(asctimer(localtimer(&rawtime)));

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-14
        • 2013-02-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多