By stuck

2014-12-17 12:26:35 8 Comments

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.

This is the code:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char * argv[]){   //File name is main.c
    if(argc != 3)
        if (argv[1] == "-s")
            girls();  //Prints "Girls"
        else if(argv[1] == "-k")
            boys();   //Prints "Boys"

In the cmd;

gcc -o gender main.c

gender -s pilkington

I enter that commands. Bu the output is always


Which part is wrong?


@Esakki Thangam 2014-12-17 12:46:44

Compare the two strings using the strcmp(s1,s2) function.

            if (strcmp(argv[1],"-s")==0)
                    girls();  //Prints "Girls"
            else if(strcmp(argv[1],"-k")==0)
                    boys();   //Prints "Boys"

@Karthikeyan.R.S 2014-12-17 12:35:50

You have to compare the string using the strcmp function. You cannot simply check the string in equality operator.

  int strcmp(const char *s1, const char *s2);

Try this in your code.

if ((strcmp(argv[1],"-s")==0)

@sharon 2014-12-17 12:33:46

if you check the argv[1] == "-s" the condition will not be true. since it is a string you can use the strcmp function.

     if(( strcmp(argv[1],"-s")) == 0)
     else if ((strcmp(argv[1],"-k")) == 0)

Try this..

@Sourav Ghosh 2014-12-17 12:27:42

In your code, argv[1] == "-s" is the erroneous part. comparison of strings cannot be done with == operator.

To compare strings, you need to use strcmp().

Your code should look like

if ( ! strcmp(argv[1], "-s")) { //code here }

if you want to check if argv[1] contains "-s" or not.

Related Questions

Sponsored Content

33 Answered Questions

46 Answered Questions

[SOLVED] How do I convert a String to an int in Java?

70 Answered Questions

[SOLVED] How to replace all occurrences of a string?

94 Answered Questions

[SOLVED] How do I make the first letter of a string uppercase in JavaScript?

18 Answered Questions

[SOLVED] How to pass command line arguments to a rake task

79 Answered Questions

[SOLVED] How do I iterate over the words of a string?

  • 2008-10-25 08:58:21
  • Ashwin Nanjappa
  • 2197128 View
  • 3032 Score
  • 79 Answer
  • Tags:   c++ string split

28 Answered Questions

[SOLVED] How to read a file line-by-line into a list?

3 Answered Questions

59 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

Sponsored Content