Klik
Klik

Reputation: 1776

Parsing Command Line Parameters in C++. I'm having a strange error

I'm having a strange error when I try parsing command line parameters. Why do I call it strange? Well, that's because I've done a lot of research about command line parsing in c++ before hand, and nobody's test code works on my visual studio 2010 IDE. When I use the debugger, I find I always get a FALSE returned when I try to check for the parameters. In the example below, it's when I do a if (argv[1] == "-in"). I tried testing it several different ways in the watch window. And I tried passing it to a string first. Or using single quotes. Then I searched around the internet and used other people's code who supposedly got it working. What am I doing wrong? Is it a setting I have set wrong in my Visual Studio environment?

This is what I had originally

#include <iostream>
#include <stdlib.h>
#include <sstream>
#include <fstream>

using namespace std;





int main(int argc, char * argv []) //Usage FileSplitter -in [filename] -sz [chunk size]
{

if (argc==5)
    {
    string strTest = argv[1];
    if ((argv[1] == "-in") && (argv[3] == "-sz"))
                 {
                        //Code here
                 }
    }
}

Anyways that was my original code. I've tried tweaking it several times and I've tried using the code from the following websites...

http://www.cplusplus.com/forum/articles/13355/ He has some examples of comparing argv[1] with a string... and he says it works.

http://www.cplusplus.com/forum/unices/26858/ Also here a guy posted some code about a comparison.. Under Ryan Caywood's post.

They won't work for me when I try to do a comparison. I am thinking about just doing a legit strcmp, but I want to know WHY my visual studio environment is not compiling like it is on everybody else's system?

Also, during debugging, I input the command line parameters in the debug section of the project properties. I don't know if that would have affected anything. I also tried building and running the project, but alas, all to no avail. Thanks in advance to anyone who can give me some good advice.

Upvotes: 1

Views: 937

Answers (2)

harmv
harmv

Reputation: 1922

You are doing the string compare incorrectly.

either do it C-style using strcmp() or (like suggested in the links you mention), convert to a C++ style string first.

if (string(argv[i]) == "stuff") { ... }

Upvotes: 1

RoneRackal
RoneRackal

Reputation: 1233

Arguments are passed in through c strings, and so if I recall correctly, comparing them using == will just compare the pointers to them. Try using strcmp() to compare two c strings, or convert both to c++ strings and compare them that way, if you must.

Upvotes: 2

Related Questions