我初学C ++目前正在尝试编写一个小程序来帮助网络设备进行robocopy备份,到目前为止我已经提出了以下代码,但是当我尝试编译时,我得到了以下错误:
31与&#39;运营商<&lt;&lt;&lt;&# in&#39;&#34; ROBOCOPY //&#34; &LT;&LT;使用oldName&#39;
我使用robocopy为所有行重复相同的错误,任何帮助将不胜感激。谢谢大家
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
string oldname;
string newname;
string userid;
char response;
cout<<"Please input old device name eg XXXXXX\n";
cin>> oldname;
cout<<"Please input new device name eg XXXXXX\n";
cin>> newname;
cout<<"Please input userid eg SP12345\n";
cin>> userid;
cout<<"Does your current device contain a D: drive? Y or N?";
cin>> response;
if (response == 'Y')
{
std::system("ROBOCOPY //"<<oldname<<"/c$/Users/"<<userid<<"/Desktop //"<<newname<<"/C$/Users/"<<userid<<"/Desktop /MIR /w:0 /r:0");
std::system("ROBOCOPY //"<<oldname<<"/c$/Users/"<<userid<<"/Favorites //"<<newname<<"/C$/Users/"<<userid<<"/Favorites /MIR /w:0 /r:0");
std::system("ROBOCOPY //"<<oldname<<"/c$/Users/"<<userid<<"/My Documents //"<<newname<<"/C$/Users/"<<userid<<"/My Documents /MIR /w:0 /r:0");
std::system("ROBOCOPY //"<<oldname<<"/d$ //"<<newname<<"/C$/Users/"<<userid<<"/Desktop/D backup /MIR /w:0 /r:0";
}
else if (response == 'N')
{
std::system("ROBOCOPY //"<<oldname<<"/c$/Users/"<<userid<<"/Desktop //"<<newname<<"/C$/Users/"<<userid<<"/Desktop /MIR /w:0 /r:0;
std::system("ROBOCOPY //"<<oldname<<"/c$/Users/"<<userid<<"/Favorites //"<<newname<<"/C$/Users/"<<userid<<"/Favorites /MIR /w:0 /r:0;
std::system("ROBOCOPY //"<<oldname<<"/c$/Users/"<<userid<<"/My Documents //"<<newname<<"/C$/Users/"<<userid<<"/My Documents /MIR /w:0 /r:0;
}
system("pause");
}
答案 0 :(得分:1)
首先,这个简单的陈述不起作用:
std::string str;
system(str); //<== expecting C-string
因为system
需要以空字符结尾的C字符串,而不是std::string
。你通过添加文字使情况变得更糟:
system("text" + str);
编译器不知道该怎么做。
其次,system
无法正确传递命令行参数。您需要CreateProcess
或ShellExecuteEx
您可能还必须传递应用程序的完整路径。例如:
#include <iostream>
#include <string>
#include <sstream>
#include <Windows.h>
void foo(std::string userid, std::string oldname, std::string newname)
{
std::stringstream ss;
ss << "c:\\Program Files (x86)\\Full Path\\Robocopy.exe"
<< " /c:\\users\\" << userid << "\\Desktop\\" << oldname
<< " /c:\\users\\" << userid << "\\Desktop\\" << newname
<< " /MIR /w:0 /r:0";
std::string commandLine = ss.str();
//examine the commandline!
std::cout << commandLine << "\n";
STARTUPINFOA si;
PROCESS_INFORMATION pi;
memset(&si, 0, sizeof(si));
si.cb = sizeof(si);
memset(&pi, 0, sizeof(pi));
char *buf = _strdup(commandLine.c_str());
CreateProcessA(0, buf, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
free(buf);
}
int main()
{
foo("x", "y", "z");
return 0;
}