我意識到根據你的評論,你已經想出了一個可行的解決方案,使用_sprintf_s
。微軟喜歡將其作爲sprintf
的一個更安全的替代方案,如果您使用C語言編寫程序,則情況屬實。但在C++中,有更安全構建字符串的方法不需要您管理緩衝區或瞭解它的最大尺寸。如果你想成爲慣用者,我建議你使用_sprintf_s
並使用C++標準庫提供的工具。
下面介紹的解決方案使用簡單的for
循環和std::stringstream
創建文件名並加載圖像。我還包括使用std::unique_ptr
進行生命週期管理和所有權語義。根據圖像的使用方式,您可能需要使用std::shared_ptr
。
#include <iostream>
#include <sstream>
#include <iomanip>
#include <vector>
#include <stdexcept>
// Just need something for example
struct Image
{
Image(const std::string& filename) : filename_(filename) {}
const std::string filename_;
};
std::unique_ptr<Image> LoadImage(const std::string& filename)
{
return std::unique_ptr<Image>(new Image(filename));
}
void LoadImages(
const std::string& path,
const std::string& filespec,
std::vector<std::unique_ptr<Image>>& images)
{
for(int i = 1; i <= 40; i++)
{
std::stringstream filename;
// Let's construct a pathname
filename
<< path
<< "\\"
<< filespec
<< std::setfill('0') // Prepends '0' for images 1-9
<< std::setw(2) // We always want 2 digits
<< i
<< ".jpg";
std::unique_ptr<Image> img(LoadImage(filename.str()));
if(img == nullptr) {
throw std::runtime_error("Unable to load image");
}
images.push_back(std::move(img));
}
}
int main()
{
std::vector<std::unique_ptr<Image>> images;
LoadImages("c:\\somedirectory\\anotherdirectory", "icon", images);
// Just dump it
for(auto it = images.begin(); it != images.end(); ++it)
{
std::cout << (*it)->filename_ << std::endl;
}
}
嘗試findfirstfile和findnextfile在sdk或cfilefind中的mfc。 – Jichao
如何以'for(int i = 1; i <= 40; i ++){...}'開頭?然後閱讀['std :: istringstream'](http://en.cppreference.com/w/cpp/io/basic_istringstream)。 –
查看關於如何使用Win32 API執行此問題的答案:http://stackoverflow.com/questions/15068475/recursive-hard-disk-search-with-findfirstfile-findnextfile-c – Asha