使用Visual C ++在批处理文件中转义Dash字符

时间:2013-08-16 00:21:30

标签: visual-c++ file-io batch-file escaping command-prompt

我正在开发一个简单的程序,其中包含计算机名称的文件由C ++文件读取,如下所示:

//Previously, the file containing names was opened and 
//getline() is in use to read each line
//note that 'line' is a string containing the current line being read 

string comp = lower(trim(line.erase(0, 2)));

//lower converts to lowercase (for later in the program) and 
//trim trims the beginning and ends of the string.  
//I have erased the first two characters, since they contain two \'s
ofstream bat;
bat.open("names_get.bat");
if (bat.is_open()) {                                     
    bat << "wmic.exe /node:"+comp+" ComputerSystem Get UserName >CompNames.txt";
    bat.close();
}

这一切都非常好。但是,使用shellexecute执行此批处理文件时遇到问题。我的问题是命令提示符遇到计算机名称,如“Owner-PC”,并将 - 作为参数,导致无效的全局切换错误。有人可以指出我正确的方向,如何在这样的事件中逃脱破折号。谢谢你,对不起这个很长的问题感到抱歉!

1 个答案:

答案 0 :(得分:0)

您应该使用comp

来包围您的"名称
 wmic.exe /node:"prefix-suffix" ComputerSystem Get Username

因此,在代码中添加\",它应该可以正常工作

if (bat.is_open()) {                                     
    bat << "wmic.exe /node:\""+comp+"\" ComputerSystem Get UserName >CompNames.txt";
    bat.close();
}