我有一个字符串,我需要做几个连接。这是我第一次在cpp中处理字符串,我需要使用的方法似乎是接受char*而不是std::string。这就是我需要做的:
String folderpath = "something";
folderpath +="/"+dbName;
mkdir(folderpath);
foo(folderpath + "/" +dbName + ".index");
bar(folderpath + "/" +dbName + ".db");
这就是我如何在c++中做到的,它看起来很糟糕。有没有更好的办法?
char* folderPath = getenv("CAVEDB_ROOT_FOLDER");
strcat(folderPath, "/");
strcat(folderPath, dbName);
mkdir(folderPath);
char* indexfile;
char* dbfile;
strcpy(indexfile, folderPath);
strcpy(dbfile, folderPath);
strcat(indexfile, "/");
strcat(indexfile, dbName);
strcat(indexfile, ".index")
strcat(dbfile, "/");
strcat(dbfile, dbName);
strcat(dbfile, ".db");
foo(indexfile);
bar(dbfile);
std::string
有c_str()
方法获取const char*
指针,例如:
std::string folderpath = "something";
folderpath += "/" + dbName;
mkdir(folderpath.c_str());
folderpath += "/" + dbName;
foo((folderpath + ".index").c_str());
bar((folderpath + ".db").c_str());
也就是说,在c++ 17及以后的版本中,您应该使用<filesystem>
库中的函数和类(在早期版本中,您可以使用boost::filesystem代替),例如:
#include <filesystem>
namespace fs = std::filesystem;
fs::path folderpath = "something";
folderpath /= dbName;
fs::create_directory(folderpath);
folderpath /= dbName;
folderpath += ".index";
foo(folderpath.string().c_str());
folderpath.replace_extension(".db");
bar(folderpath.string().c_str());