0

Everytime I compile this C++ code I get a thread exception I can't understand. What is wrong here?

#include <iostream>
#include <string>
using namespace std;

int main(int argc, char* argv[]) {
    string arg = argv[1];

    if (arg == "-r")
        cout << "First arg is -r" << endl;

    return 0;
}  
thisiscrazy4
  • 1,905
  • 8
  • 35
  • 58
  • 1
    Add the exception you obtain it could help. – Michaël Nov 27 '12 at 10:44
  • "exception when compiling"? You mean a compiler error? Or an exception when you run the program? Please edit your question to include more details, including all errors from the compiler and linker. – Some programmer dude Nov 27 '12 at 10:48
  • I'm not sure exactly what it is but [here's](https://www.dropbox.com/s/mchl6iq81d3mtnz/exception.png) a screenshot of what comes up once its done compiling. – thisiscrazy4 Nov 27 '12 at 10:49
  • It is failing on strlen. Are you passing the command line argument while invoking the binary. – nanda Nov 27 '12 at 10:54

1 Answers1

0

You forgot to check argc>=2 before assigning argv[1] to the string arg.
Are you sure you are running this program with passing a parameter?

A possible correction:

#include <iostream>
#include <string>
using namespace std;

int main(int argc, char* argv[]) 
{
    if(argc<2)
    {
      cerr << "Not enough parameters" << endl;
      abort();
    }

    string arg = argv[1];

    if (arg == "-r")
        cout << "First arg is -r" << endl;

    return 0;
}
Barney Szabolcs
  • 11,846
  • 12
  • 66
  • 91
  • Thanks, that's my problem since I was just building and running without adding any parameters. – thisiscrazy4 Nov 27 '12 at 10:57
  • 1
    Here's a link that can help with setting up command line arguments. [(link)](http://stackoverflow.com/questions/5025256/how-do-you-specify-command-line-arguments-in-xcode-4) – Barney Szabolcs Nov 27 '12 at 11:05