"@"在基于 ctime 的函数中打印出来
'@' printed out in a ctime based function
我正在开发一个头文件,该文件具有打印日期的功能。以下操作完成了上述操作:
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.:很抱歉我的英语不好
- 回溯C++不打印函数,因此文件
- 重写打印函数而不是覆盖基类
- 从模板创建通用打印函数,以打印基元数据类型变量的值
- 打印传递给打印函数的矢量
- 如何使用重新定义的打印函数打印Lua表?
- 调用和打印函数,在 C++ 中返回数组
- Lua C API 自定义打印函数,在字符串中传递空格时不调用
- C++二叉树打印函数实现
- 如何从主 C++ 向模板类中的方法发送打印函数
- 如果我不打印函数参数的值,则将其转换为等于零
- 打印函数模板的内容进行类指针
- C++打印函数的结果?
- 打印 C++ 函数
- 编写一个通用打印函数来打印数组
- 用于打印函数进入和退出跟踪的宏
- 每当尝试打印函数变量时,C++ cout 错误
- GDB:当没有可用的名称符号时,如何打印函数参数值
- 在lua中重新定义打印函数时出现问题
- 打印函数会返回一个意外值,原因是什么
- IntStack的C++递归打印函数