连接C++中的写入参数

Concatenate write parameters in C++

本文关键字:参数 C++ 连接      更新时间:2023-10-16

我需要连接write函数中的参数。我该怎么做?

示例:ofstream write(newFolder concat "/newfile.txt");

mkdir(newFolder);
ofstream write (wantTo "concat here");
write << "Sup mo fo";
write.close();

如果newFolder是std::字符串,则可以简单地使用newFolder + "/newfile.txt"。不过,您必须确保newFolder不会以/结尾。如果在write函数中需要char*,则可能需要在std::string中使用c_str()函数。

虽然使用std::string是首选方法,但要小心,因为标准库的旧版本不支持以std::string为参数的open方法。

如果在使用std::string时对open的调用中出现错误,则必须分两步执行:

std::string newFolder = "/path/to/folder";
mkdir(newFolder.c_str(), 0644);  // The 'mkdir'  function wants 'const char *'
// Has to concatenate strings here if your standard library is too old
std::string folderAndFile = newFilder + "/filename";
std::ofstream output(folderAndfile.c_str());