0

I have a program that needs to use variables that should be set when the program is called from the command line. I want the user to be able to specify options -r, -o, -s, and -p along with some integer. I've never dealt with command line arguments before but after doing some research I came up with the following:

int main(int argc, char *argv[]){
    for(k = 1; k < argc; k = k+2){
        if(std::string(argv[k]) == "-r"){
           n = atoi(std::string(argv[k+1]));
        }else if(std::string(argv[k]) == "-o"){
           o = atoi(std::string(argv[k+1]));
        }else if(std::string(argv[k]) == "-s"){
           p = atoi(std::string(argv[k+1]));
        }else{
          n = 1; o = 2; p = 3;
        }
    }
}

My idea is that the user would call the program like so:

$ ./my_program -r 1000 -o 10000000 -s 1

in order to set the variables in my program accordingly. However, when I try to compile this with my makefile, I get an error:

    error: std undeclared (first use in this function)
        if(std::string(argv[k]) == "-r"){
           ^

There are many more but I can't type them all. I'm sure if I figure out this error I can figure out the others. Why doesn't C like me?

EDIT:

As a quick note, I did include , but this does not fix any of the errors and the output when calling make is still the same.

12
  • 1
    #include <string> (you tagged C, but the code you posted is C++) Commented Mar 9, 2014 at 6:54
  • Including this does not fix any of the errors I have. Commented Mar 9, 2014 at 6:57
  • Then you should have said so, and included the "fatal error," in your question. We can't help you solve problems without all the information. Commented Mar 9, 2014 at 6:58
  • 3
    std::string does not exist in C; to compare strings you would use the strcmp() function. You may want to consider using a library that already has commandline arguments worked out, such as GNU getopt. Commented Mar 9, 2014 at 7:04
  • 1
    Possible duplicate of Parsing command-line arguments? There are also many other questions that this could be a duplicate of. Commented Mar 9, 2014 at 7:18

1 Answer 1

2

You should use getopt() here. The getopt() and getopt_long functions automate some of the chore involved in parsing typical unix command line options. It will save you all the effort.

http://www.ibm.com/developerworks/aix/library/au-unix-getopt.html

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.