问题是如何检查字符串filenum的长度,此字符串将更改,例如,它可能为'1',如何将4个前导零加到'1'上,从而使filenum ='00001',依此类推,说filenum ='21'并添加三个前导零的filenum ='00021'我一直希望文件num的长度为5。另外,在获取新值之后,如何将该值用于路径。任何帮助将不胜感激!

这是到目前为止我得到的但我收到此错误(错误C2665:'basic_string ::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");
    }

}

最佳答案

您正在尝试调用不存在的std::string构造函数。您要调用的构造函数需要一个char作为输入,但是您正在传递给它一个char*字符串文字。另外,您的if语句无论如何都是错误的,并且可能会导致错误。您只需要1个if即可处理所有情况。而且您甚至没有使用所创建的filenums变量,而应该将填充添加到filenum本身。

试试这个:

std::string filenum = m_csFileName;
if (filenum.length() < 5)
    filenum = std::string(5 - filenum.length(), '0') + filenum;

关于c++ - 如何检查字符串的长度并返回以零开头的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33219634/

10-11 18:30