我知道要在C中使用命令行参数,你可以这样做:
int main(int argc, char **argv)
{
//use argc and argv
}
Run Code Online (Sandbox Code Playgroud)
今天,我在想这件事,我意识到我从来没有看到他们所谓的argc和argv.要求他们被称为这个或仅仅是惯例吗?如果需要,为什么会这样呢?
我可以这样做:
int main(int length, char**myinput){
//use length as you would argc and myinput
// as you would argv
}
Run Code Online (Sandbox Code Playgroud)
我还没有机会写一个程序来测试它.
我想从命令行参数获取文件名,所以我可以将它传递给文件打开函数,但是,argv []默认情况下似乎是const char**类型,即使它被定义为"const char*argv" []"在主要论点中.我的函数需要const char*,有没有办法转换这两个,还是什么?
int main(int argc, const char *argv[]) {
memory Memory;
Memory.loadROM(argv); // Error 'argument of type "const char **" is incompatible with parameter of type "const char *"'
}
Run Code Online (Sandbox Code Playgroud) 我知道,因为argc是参数的数量,它可以是一个int.但为什么应该argv是char pointer类型?这是否意味着我无法传递整数参数并argv[1]在数学运算中使用?
编辑:为了使它更清晰,是否可以写出像int* argv[].是否argv已定义为char*无法更改的类型?
我正在搞乱C/C++中的项目,我注意到了这一点:
C++
#include <iostream.h>
int main (int argc, const char * argv[]) {
// insert code here...
cout << "Hello, World!\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
和
C
#include <stdio.h>
int main (int argc, const char * argv[]) {
// insert code here...
printf("Hello, World!\n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
所以我总是想知道这个,这些默认参数在int main下的C/C++中究竟做了什么?我知道应用程序仍然会在没有它们的情况下编译,但它们的用途是什么?
我写了这个简单的代码来了解参数系统是如何工作的。我将文本文件拖到.exe文件,并得到2作为输出,而不是我期望的1。为什么是2?Arg 1是.exe本身吗?如何找到参数的文件名?
#include<iostream>
using namespace std;
int main(int argc, char* argv[])
{
int i = 0;
const int max = 100000;
if (argc > 0)
{
cout<< argc <<endl;
}
cin.get(); cin.get();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
还有一个问题。我在哪里可以告知如何访问每个参数并使用这些信息。我的目标是打开所有作为参数传递给.exe的文件。
这不是一个重复的问题,我问为什么当您传递1个参数时返回2。链接中的问题是另一个...