"@"在基于 ctime 的函数中打印出来

'@' printed out in a ctime based function

本文关键字:打印 函数 ctime      更新时间:2023-10-16

我正在开发一个头文件,该文件具有打印日期的功能。以下操作完成了上述操作:

    char Date(string date_format){
    if(date_format == "ggddyyyy"){
                time_t t = time(0);
    struct tm * now = localtime( & t );
    cout << (now->tm_mday) << '/'
     << (now->tm_mon + 01) << '/'
     << (now->tm_year + 1900);
    }
    if(date_format == "mmddyyyy"){
                time_t t = time(0);
    struct tm * now = localtime( & t );
    cout << (now->tm_mon + 01) << '/'
    << (now->tm_mday) << '/'
    << (now->tm_year + 1900);
    }

因此,要在.cpp文件中使用此函数,必须编写

    cout << Date("ddmmyyyy") << endl;

它将打印出"6/5/2016"它将打印意大利日期格式,如果我设置英语格式(mm\dd\yyyy),它将在日期末尾打印出波浪号:2016年5月6日@也许这是一个愚蠢的错误,也许是因为backslahed,这让编译器认为我正在尝试使用类似"\n"的转义序列,但不存在带有"\m"或"\d"的转义顺序,所以我认为这不是问题。提前谢谢。

您的代码有很多问题。

1) 您传递了格式"dd\mm\yyyy",但Date()中未检查此格式(您检查了"gg\dd\yyyy"answers"mm\dd\yyyy")

2) 函数被声明为返回char的函数,但中没有return

3) 正如Kaz所建议的,你应该逃离每一个''加倍它(所以"g\\dd\\yyyy","mm\\dd\\yyyy",等等)

4) 我认为您应该编写一个函数来创建并返回std::string,避免使用输出流。您的实际函数用std::cout编写,但返回(不要返回,请参阅第2点)一个char;返回值的含义是什么?如果Data()std::cout()中写入,则应该以这种方式使用

Data("dd\mm\yyyy");
std::cout << std::endl;

如果Data()返回std::string,则可以编写

std::cout << Data("dd\mm\yyyy") << std::endl;

我建议Data()应该返回一个std::string,这样你就可以将它与其他流一起使用;std::cerr,例如

std::cerr << Data("dd\mm\yyyy") << std::endl;

5) 不需要复制CCD_ 14/CCD_;在两种情况下都是相等的

我建议使用以下版本的

std::string Date (std::string const & format)
 {
   std::ostringstream  oss;
   time_t t = time(0);
   tm * now = localtime( & t );
   if ( "gg\dd\yyyy" == format )
      oss << (now->tm_mday) << '/'
         << (now->tm_mon + 01) << '/'
         << (now->tm_year + 1900);
   else if ( "mm\dd\yyyy" == format )
      oss << (now->tm_mon + 01) << '/'
         << (now->tm_mday) << '/'
         << (now->tm_year + 1900);
   // else if .... (other formats?)
   else
      oss << "unrecognized format";
   return oss.str();
 }

或者,如果您使用C++11或C++14,则可以使用std::to_string(),避免使用std::ostringstream

std::string Date (std::string const & format)
 {
   std::string  str;
   time_t t = time(0);
   tm * now = localtime( & t );
   if ( "gg\dd\yyyy" == format )
      str = std::to_string(now->tm_mday) + "/"
         + std::to_string(now->tm_mon + 01) + "/"
         + std::to_string(now->tm_year + 1900);
   else if ( "mm\dd\yyyy" == format )
      str = std::to_string(now->tm_mon + 01) + "/"
         + std::to_string(now->tm_mday) + "/"
         + std::to_string(now->tm_year + 1900);
   // else if .... (other formats?)
   else
      str = "unrecognized format";
   return str;
 }

p.s.:很抱歉我的英语不好