问题是我如何检查我的字符串 filenum 的长度,这个字符串会改变,例如它可能是 '1' 我怎样才能在 '1' 上添加 4 个前导零使 filenum = '00001' 等等假设 filenum = '21' 并添加三个前导零的 filenum ='00021' 我总是希望文件 num 的长度为 5。此外,在我获得新值之后,我如何将该值用于我的路径。任何帮助将不胜感激!
这是我目前所拥有的,但我得到了这个错误(错误 C2665:'basic_string< char,struct std::char_traits, class std::allocator >::basic_string
void CJunkView::OnCadkeyButton()
{
CString dbdir15 = "Dir15";
CString dbdir14 = "Dir14";
std::string filenum = m_csFileName;
//CString fileName3 = "15001.prt";
CString dbyear = m_csDatabaseYear;
if(filenum.length() < 1)
{
std::string filenums = std::string(5 - filenum.length(), "0") + filenum;
}
else if(filenum.length() < 2)
{
std::string filenums = std::string(4 - filenum.length(), "0") + filenum;
}
else if(filenum.length() < 3)
{
std::string filenums = std::string(3 - filenum.length(), "0") + filenum;
}
else if(filenum.length() < 4)
{
std::string filenums = std::string(2 - filenum.length(), "0") + filenum;
}
else if(filenum.length() < 5)
{
std::string filenums = std::string(1 - filenum.length(), "0") + filenum;
}
if(m_csDatabaseYear == "15")
{
CString fileToOpen = "\"\\\\CARBDATA\\VOL1\\Docs\\PREFORM\\15T\\" + dbdir15 +"\\" + filenum + "\"";
CString exePath = "\"C:\\CK19\\Ckwin.exe\"";
CString cmd = "start " + exePath + ", " + fileToOpen;
system (cmd.GetBuffer(cmd.GetLength() + 1));
//PrintMessage("File Found 2015");
}
//file not found tell user file not found.
else if(m_csDatabaseYear == "14")
{
CString fileToOpen = "\"\\\\CARBDATA\\VOL1\\Docs\\PREFORM\\14T\\" + dbdir14 +"\\" + filenum + "\"";
CString exePath = "\"C:\\CK19\\Ckwin.exe\"";
CString cmd = "start " + exePath + ", " + fileToOpen;
system (cmd.GetBuffer(cmd.GetLength() + 1));
//PrintMessage("File Found 2015");
}
else
{
PrintMessage("File Not Found");
}
最佳答案
如果您想使用 CString
类(因为您的帖子似乎标有 "visual-c++"
并且您似乎已经在使用 CString
在您的代码中 - 可能在 Win32 层边界处),您可以使用 CString::Format()
method .
特别是,您可以传递一个 %05d
字符串格式说明符,这意味着您需要一个 5 位数字的填充:
int n = 1; // or whatever...
CString paddedNum;
paddedNum.Format(L"%05d", n);
// paddedNum contains "00001"
然后,您可以构建完整的路径/文件名,只需使用 CString 的 operator+
来连接几个子字符串。
或者您仍然可以使用 CString::Format()
,为完整路径/文件名指定更复杂的字符串格式。
您可以使用 printf()
format specification syntax对于 CString::Format()
。
关于c++ - 如何检查字符串的长度并返回带有前导零的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33219634/