在命令行参数中使用引号

Using Quotes in command line arguments

本文关键字:命令行 参数      更新时间:2023-10-16

我尝试编写以命令行参数作为输入的程序。当我在 cmd 中的引号内使用命令行参数时,例如

g++ -o filename.exe filename.cpp // for compiling

filename.exe "2 -1 0 2 -3" // run command

答案不正确。但是当我使用

g++ -o filename.exe filename.cpp // for compiling

filename.exe 2 -1 0 2 -3 // run command

答案是正确的...为什么会这样...有人可以建议一些东西来纠正它吗?我使用 C++ 进行编码,使用 cmd 来编译、运行和测试。

你传递所有用空格分隔的命令行参数,但如果 参数本身有一个空格,那么你可以通过传递这样的参数 将它们放在双引号">或单引号 ''中。

所以

"2 -1 0 2 -3"  // One argument

2 -1 0 2 -3    // Five arguments

您可以将它们组合在一起

"2 -1 0" 2 -3  // Three arguments

命令行参数使用main()函数参数进行处理,其中 argc 是指传递的参数数,而 argv[] 是一个指针数组,指向传递给程序的每个参数。

int main(int argc, char *argv[]) { ... }

其中argv[0]始终是程序名称。在您的情况下filename.exe.