在 C 中使用 argv? [英] Using argv in C?
问题描述
对于作业,我需要为我的 C 程序提供命令行参数.我之前(在 C++ 中)使用过 argc/argv 没有问题,但我不确定 C 风格的字符串是否会影响它的工作方式.这是我的主要内容的开始:
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:
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;
}
}
所以我将我的程序称为program.exe -e myargstuff",但我得到错误:不正确的用法..."输出,即使我的 printf() 告诉我 argv[1] 是-电子".请帮忙?谢谢!
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!
推荐答案
行
if(argv[1]=="-e"){
比较指针,而不是字符串.改用 strcmp 函数:
compares pointers, not strings. Use the strcmp function instead:
if(strcmp(argv[1],"-e")==0){
这篇关于在 C 中使用 argv?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!