【问题标题】:char[] to CString Conversionchar[] 到 CString 的转换
【发布时间】:2013-05-31 07:47:17
【问题描述】:

我有时间使用char[] 格式,但我需要将其转换为CString。这是我所拥有的,但它不起作用:

GetSystemTime(&t);
char time[60] = "";
char y[20],mon[20],d[20],h[20],min[20],s[20];

sprintf(y, "%d", t.wYear);
sprintf(d, "%d", t.wDay);
sprintf(mon, "%d", t.wMonth);
sprintf(h, "%d", t.wHour+5);
sprintf(min, "%d", t.wMinute);
sprintf(s, "%d", t.wSecond);

strcat(time,d);
strcat(time,"/");
strcat(time, mon);
strcat(time,"/");
strcat(time, y);
strcat(time," ");
strcat(time,h);
strcat(time,":");
strcat(time, min);
strcat(time,":");
strcat(time, s);

CString m_strFileName = time;

任何帮助..:( ?

【问题讨论】:

  • “它不起作用”非常模糊。你有编译错误吗?它会崩溃吗?结果错了吗?

标签: c++ char cstring


【解决方案1】:

如果您有文件扩展名,那么最好的放置位置是在格式化日期字符串时在 sprintf/CString::Format 调用中。 此外,通常在格式化文件名的日期时,会以相反的顺序 yyyy/mm/dd 进行,以便在 Windows 资源管理器中正确排序。

1 在我进入一些代码之前的最后一件事:Windows 中的文件名存在无效字符,其中包括斜杠字符 [EDIT] 和冒号字符 [/EDIT]。通常使用点或破折号代替文件名。 我的解决方案使用您使用的斜杠和日期格式,与您的代码保持一致,但如果您将斜杠用于文件名,则至少应该更改斜杠。

让我为您提供一些解决方案:

1:与你的相似:

char time[60];
sprintf(time, "%u/%u/%u %u:%u:%u", t.wDay, t.wMonth, t.wYear, t.wHour + 5, t.wMinute, t.wSecond);
CString m_strFileName(time); //This uses the CString::CString(const char *) constructor
//Note: If m_strFileName is a member variable of a class (as the m_ suggests), then you should use the = operator and not the variable declaration like this:
m_strFileName = time; //This variable is already defined in the class definition

2:使用CString::Format

CString m_strFileName; //Note: This is only needed if m_strFileName is not a member variable of a class
m_strFileName.Format("%u/%u/%u %u:%u:%u", t.wDay, t.wMonth, t.wYear, t.wHour + 5, t.wMinute, t.wSecond);

3:为什么要使用 CString?

如果不是类的成员变量,则不需要使用CString,直接使用时间即可。

char time[60];
sprintf(time, "%u/%u/%u %u:%u:%u", t.wDay, t.wMonth, t.wYear, t.wHour + 5, t.wMinute, t.wSecond);
FILE *pFile = fopen(time, "w");
//or...
HANDLE hFile = CreateFile(time, ...);

更新:回答您的第一条评论:

NO CString::GetBuffer 用于获取可以写入的 CString 的可变缓冲区,通常作为 sprintf、GetModuleFilename 等函数的缓冲区。

如果您只想读取字符串的值,请像这样使用强制转换运算符:

CString str("hello");
printf("%s\n", (LPCSTR)str); //The cast operator here gets a read-only value of the string

【讨论】:

  • 现在如果我可以将它转换成 CString,那么我将使用 CString 的 GetBuffer() 方法将它转换成 LPSTR。不幸的是,我在这些类型的转换方面很差。
【解决方案2】:

您可以使用 std::ostringstream 和 std::string 将时间转换为字符串。 像这样的东西。我已经展示了几秒钟,你可以做几小时、几分钟等。

int seconds;
std::ostringstream sec_strm;
sec_strm << seconds;
std::string sec_str(sec_strm.c_str());

【讨论】:

    猜你喜欢
    • 2011-08-06
    • 2015-08-07
    • 2011-11-02
    • 2020-06-12
    • 2010-10-25
    • 2015-05-14
    • 1970-01-01
    • 2010-10-08
    相关资源
    最近更新 更多