views:

306

answers:

4

I know how to get the parameters from the command line. I also know how to print them out.

The problem I'm having is how to compare the parameters from the argv[] array to a string. The progam runs but never returns a result where the parameter string is equal to the one I'm looking for.

Thanks in advance.

// Testing.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream> 
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    for (int i = 0; i < argc; i = i + 1)
    {       
    if (argv[i] == _T("find"))
    {
        wcout << "found at position " << i << endl;
    }
    else
    {
        wcout << "not found at " << i << endl;
    }
}

return 0;
}
+1  A: 

You need to use strcmp function for the compare. what you're doing write now is just comparing the pointers. please note that strcmp returns 0 if the strings are equal.

#include "stdafx.h"
#include <iostream> 
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    for (int i = 0; i < argc; i = i + 1)
    {       
    if (_tcscmp(argv[i], _T("find")==0)
    {
        wcout << "found at position " << i << endl;
    }
    else
    {
        wcout << "not found at " << i << endl;
    }
}
sonofdelphi
A: 

if (argv[i] == _T("find")) should be if (strcmp(argv[i], "find") == 0)

David Titarenco
A: 
if (argv[i] == _T("find")) 

This will only the compare the pointers argv[i] and pointer pointed to "find". What you need is to compare the strings. you can use strcmp, ( wcscmp, for unicode)

  0 == wcscmp( argv[i], _T("find")) 
aJ
+1  A: 

As the other answers say, strcmp() or wsccmp() depending on whether you are compiling with UNICODE defined, which _tccmp() from will do for you.

Simon Buchan