c++ - C 中是否有相当于 %* 或 Environment.CommandLine 的东西?

标签 c++ c command-line-arguments

换句话说,有没有办法在单个字符串中捕获整个命令行(甚至命令行的参数部分),包括所有分隔符?

我明确不寻找涉及连接 argv 元素的解决方案。 此类解决方案假定有关分隔符或参数格式的某些信息。

例如,让我们看下面的程序:

#include <stdio.h>

int main(int argc, char** argv){
    int i;
    for (i = 0; i < argc; i++)
        puts(argv[i]);
}

如果我像这样运行它:

 Test.exe 1 2

我得到输出:

 Test.exe
 1
 2

这不是问题,但是当我这样运行时:

Test.exe "1" "2"

我得到了完全相同的输出,这是一个问题。基本上,我试图获取作为命令行发出的逐字字符串。

最佳答案

C 中没有内置方法可以将命令行(或参数)作为单个字符串检索,所有引号都完好无损,至少语言标准没有定义。部分问题在于 argv 数组的定义,部分问题在于您的 shell 在将参数传递给程序之前执行的操作(例如删除引号):

5.1.2.2.1 Program startup
...
— If the value of argc is greater than zero, the array members argv[0] through argv[argc-1] inclusive shall contain pointers to strings, which are given implementation-defined values by the host environment prior to program startup. The intent is to supply to the program information determined prior to program startup from elsewhere in the hosted environment. If the host environment is not capable of supplying strings with letters in both uppercase and lowercase, the implementation shall ensure that the strings are received in lowercase.

强调我的。

可能有特定于平台的扩展可以满足您的需求,但我个人并不知道有任何扩展。

关于c++ - C 中是否有相当于 %* 或 Environment.CommandLine 的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10196406/

相关文章:

c++ - mycout 自动结束

c++ - 非阻塞 worker - 中断文件复制

c++ - 使用++ 作为通过类成员访问语句的前缀不会导致错误

c - NSAddImage 的替换(在 GLLoadGen 中)

c - 为什么竞争条件会在循环中发生?

C++ 面试 - 测试潜在候选人

c - 发送到 : Resource temporarily unavailable (errno 11)

c# - 在 C# 中处理命令行选项的最佳方式

python - 具有多个常用选项的命令使用自定义装饰器进入一个参数

linux - bash getopts 验证选项