C++ 如何连接两个指针字符?
我正在使用xcopy构建一个快速复制应用程序。我想把两个变量源和目标传递给系统;我正在这样努力C++ 如何连接两个指针字符?,c++,c++11,C++,C++11,我正在使用xcopy构建一个快速复制应用程序。我想把两个变量源和目标传递给系统;我正在这样努力 char *source = "D:\\SOFTWARE\\Internet"; char *destination = " D:\\test /s /e /d /y"; system("xcopy "+source+destination); 但它不起作用。它在java中运行良好。相同的代码。谢谢。您需要使用字符串标题中的std::st
char *source = "D:\\SOFTWARE\\Internet";
char *destination = " D:\\test /s /e /d /y";
system("xcopy "+source+destination);
但它不起作用。它在java中运行良好。相同的代码。谢谢。您需要使用字符串标题中的std::string。此外,还需要从字符串转换为常量字符指针
#define _CRT_SECURE_NO_DEPRECATE
#include <cstdlib>
#include <string>
int main()
{
using namespace std;
string str{ "dir" };
string str2{ " /w" };
string final_string = str + str2;
char* cstr = new char[final_string.size() + 1];
strcpy(cstr, final_string.c_str());
system(cstr);
}
重写Mike的代码,以消除我们在审查代码时倾向于标记的所有问题
#include <string>
#include <cstdlib>
using std::string;
int main()
{
const string str{ "dir" };
const string str2{ " /w" };
const string final_string = str + str2;
std::system(final_string.c_str());
}
字符串连接的另一种方式是使用。以下代码中引用了源路径和目标路径,以便更安全:
#include <sstream>
int main() {
const char *source = "\"D:\\SOFTWARE\\Internet\"";
const char *destination = " \"D:\\test\" /s /e /d /y";
std::ostringstream cmd;
cmd << "xcopy " << source << destination;
system(cmd.str().c_str());
}
那不行。C字符串的一个选项是char cmd[1024];snprintfcmd,sizeof cmd,%s%s,源,目标;systemcmd;。使用std::string而不是C样式的字符指针。还要注意,您的参数没有引号,可能会被shell误解。代码对我不起作用。请给出一个错误:没有匹配的函数用于调用systemdon't write using namespace std;。在很多地方使用const。不要使用全新的。为了使用system,您不需要复制字符串内容,而只需使用final_string.c_str。@coder_haslib include文件将名称引入std名称空间中,并且可能将它们作为全局名称,也可能不将它们作为全局名称。在这一个文件上拧螺丝钉。感谢@JDługosz的更正。
#include <sstream>
int main() {
const char *source = "\"D:\\SOFTWARE\\Internet\"";
const char *destination = " \"D:\\test\" /s /e /d /y";
std::ostringstream cmd;
cmd << "xcopy " << source << destination;
system(cmd.str().c_str());
}