如何正确比较的命令行参数? [英] How to properly compare command-line arguments?
本文介绍了如何正确比较的命令行参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图写一个C code这需要论据为主;因此,当我写在cmd中一些字符串,程序在做里面出头。但是,我做错了什么,我无法找到它。
I am trying to write a C code which takes arguments in main; thus when I write some strings in cmd, the program doing somethings inside it. But I am doing something wrong and I can't find it.
这是code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char * argv[]){ //File name is main.c
if(argc != 3)
printf("Wrong!!!!!!!!!");
else
if (argv[1] == "-s")
girls(); //Prints "Girls"
else if(argv[1] == "-k")
boys(); //Prints "Boys"
else
printf("OMG!!");
}
在cmd;
的gcc -o性别的main.c
性别-s皮尔金顿
我输入的命令。卜输出总是
I enter that commands. Bu the output is always
妈呀!
哪一部分是错误的?
推荐答案
在您的code,的argv [1] ==-s
是错误的部分。字符串比较不能用做==
运营商。
In your code, argv[1] == "-s"
is the erroneous part. comparison of strings cannot be done with ==
operator.
要比较字符串,你需要使用 的strcmp()
To compare strings, you need to use strcmp()
.
您code应该像
if ( ! strcmp(argv[1], "-s")) { //code here }
如果你想检查是否的argv [1]
包含。 - 的
与否
if you want to check if argv[1]
contains "-s"
or not.
这篇关于如何正确比较的命令行参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文