gpt4 book ai didi

c++ - 传递包含空格和引号的参数字符串

转载 作者:行者123 更新时间:2023-11-30 02:47:33 26 4
gpt4 key购买 nike

使用 QProcess::startDetached ,我需要将来自另一个进程的动态参数列表传递给启动进程。

const QString & prog, const QStringList & args, const QString & workingDirectory ...)

Note that arguments that contain spaces are not passed to the process as separate arguments.

...

Windows: Arguments that contain spaces are wrapped in quotes. The started process will run as a regular standalone process.

我有一个包含以下文本的字符串,它来自一个没有任何控制的外部程序:

-c "resume" -c "print 'Hi!'" -c "print 'Hello World'"

我需要将上面的字符串传递给 QProcess::startDetached 以便启动程序像上面的字符串一样捕获它。

我是否必须解析字符串并构建字符串列表?或者谁有更好的解决方案?

最佳答案

您根本不必为参数使用 QStringList,因为有这个重载函数:-

bool QProcess::startDetached(const QString & program)

正如文档所述:-

Starts the program program in a new process. program is a single string of text containing both the program name and its arguments. The arguments are separated by one or more spaces.

The program string can also contain quotes, to ensure that arguments containing spaces are correctly supplied to the new process.

您可能需要将“替换为\”,但您可以从 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;
}

关于c++ - 传递包含空格和引号的参数字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22685877/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com