C语言 在 C 中使用 argv?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2300744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using argv in C?
提问by Joe
For an assignment, I am required to have command line arguments for my C program. I've used argc/argv before (in C++) without trouble, but I'm unsure if C style strings are affecting how this works. Here is the start of my main:
对于作业,我需要为我的 C 程序提供命令行参数。我之前(在 C++ 中)使用过 argc/argv 没有问题,但我不确定 C 风格的字符串是否会影响它的工作方式。这是我的主要内容的开始:
int main(int argc, char *argv[]){
if(argc>1){
printf("0 is %s, 1 is %s\n",argv[0],argv[1]);
if(argv[1]=="-e"){
// Do some stuff with argv[2]
system("PAUSE");
}
else{
printf("Error: Incorrect usage - first argument must be -e");
return 0;
}
}
So I am calling my program as "program.exe -e myargstuff" but I am getting the "Error: Incorrect Usage..." output, even though my printf() tells me that argv[1] is "-e". Some help, please? Thanks!
所以我将我的程序称为“program.exe -e myargstuff”,但我得到了“错误:不正确的用法...”输出,即使我的 printf() 告诉我 argv[1] 是“-e”。请帮忙?谢谢!
回答by jgottula
回答by Dawid
Change:
改变:
if(argv[1]=="-e"){
to
到
if(strcmp(argv[1], "-e") == 0){
and include string.h.
并包括string.h.
回答by Carl Norum
回答by goatlinks
回答by Laurence Gonsalves
You can't use ==to compare strings like that in C. That's just comparing the addresses of argv[1] and your literal, which are pretty much guaranteed to be different.
你不能==用来比较像 C 中那样的字符串。那只是比较 argv[1] 和你的文字的地址,它们几乎可以保证是不同的。
Use strcmpinstead. eg:
使用strcmp来代替。例如:
if (!strcmp("-e", argv[1])) {
回答by zneak
The prototype of the main function says you're dealing with char*pointers. In C, there is no operator overloading; therefore, ==between two char*will test if they point to the same place. This is not the case, and is rarely the case at all. Use the strcmp(the reference for the function is valid even though it points to a C++ site) function from <string.h>:
main 函数的原型表示您正在处理char*指针。在 C 中,没有运算符重载;因此,==两者之间char*将测试它们是否指向同一个地方。事实并非如此,而且这种情况很少发生。使用strcmp(该函数的引用是有效的,即使它指向 C++ 站点)函数来自<string.h>:
strcmp(argv[1], "-e") == 0

