传递参数字符串,其中包含空格和引号
Passing argument string which contains spaces and quotes
使用QProcess::startDetached
,我需要将来自另一个进程的动态参数列表传递给启动进程。
const QString & prog, const QStringList & args, const QString & workingDirectory ...)
注意,包含空格的参数不会传递给进程作为单独的参数。
…
Windows:包含空格的参数用引号括起来。的已启动的进程将作为一个常规的独立进程运行。
我有一个字符串,它包含下面的文本,它来自一个外部程序,没有任何控制:
-c "resume" -c "print 'Hi!'" -c "print 'Hello World'"
我需要将上面的字符串传递给QProcess::startDetached
,以便启动程序捕获它与上面的字符串相同。
我必须解析字符串并构建字符串列表吗?或者有人有更好的解决方案吗?
您根本不必为参数使用QStringList,因为有这个重载函数:-
bool QProcess::startDetached(const QString & program)
如文档所述:-
在新进程中启动程序程序。program is 是一个包含程序名及其参数的文本字符串。参数之间用一个或多个空格分隔。
程序字符串也可以包含引号,以确保包含空格的参数被正确地提供给新进程。
您可能需要将"替换为",但您可以从QString
中做到这一点,
您可以使用parseCombinedArgString
(从Qt的源代码)来解析:
QStringList parseCombinedArgString(const QString &program)
{
QStringList args;
QString tmp;
int quoteCount = 0;
bool inQuote = false;
// handle quoting. tokens can be surrounded by double quotes
// "hello world". three consecutive double quotes represent
// the quote character itself.
for (int i = 0; i < program.size(); ++i)
{
if (program.at(i) == QLatin1Char('"'))
{
++quoteCount;
if (quoteCount == 3)
{
// third consecutive quote
quoteCount = 0;
tmp += program.at(i);
}
continue;
}
if (quoteCount)
{
if (quoteCount == 1)
inQuote = !inQuote;
quoteCount = 0;
}
if (!inQuote && program.at(i).isSpace())
{
if (!tmp.isEmpty())
{
args += tmp;
tmp.clear();
}
}
else
{
tmp += program.at(i);
}
}
if (!tmp.isEmpty())
args += tmp;
return args;
}
是的,您必须"解析"字符串,在正确的位置拆分它,并将每个子字符串输入到您传递给函数的QStringList
对象中。
相关文章:
- 如何在c++中使用system()来运行包含空格的python脚本
- 如何存储包含多个空格的字符串 c++
- 如何处理包含空格的 cin 的用户输入?
- 如何在C++的凯撒密码程序中包含空格?
- 如何包含整数之间的空格作为输出
- 访问包含P的有效索引时返回空格的C++字符串
- C++ 逐行从文件(包含空格)读取数据
- 使用分隔符空格解析字符串,但字符串也包含空格
- C++:按制表符拆分字符串,但包含空格
- 崇高文本 3 - 在终端中编译并运行 C++ 程序(路径包含空格)
- 如何接受字符串中包含空格的字符串向量
- 如何 ROT 加密包含空格的字符串?
- 读取可能包含空格的字符串
- 如何将字符串与包含空格的短语一起使用
- 无法获取包含C++空格的输入
- 为什么这个 leveldb 代码会截断包含空格的"std::string"?
- 使用包含给定空格的路径启动程序
- 修改 gettext .pot 文件输出以排除空字符串或仅包含空格的字符串
- 如何从包含空格的 stdin 输入字符串
- c++中包含许多空格的拆分字符串