0

I was trying to understand command line parameters in c++ and ran into an (naively) unexpected issue, so I tried to work out what the issue was by creating a version of my code that uses auto and a range for loop as well as a version with std::string and range for loop. Only the latter gives the expected result. The code compiles fine and I don't get any warnings.

It seems like c++ just won't let me compare argv[] with validCharArgs[]. I tried it both with and without const.

#include <iostream>
#include <string>

int main(int argc, char* argv[])
{
    const char* validCharArgs[3];
    validCharArgs[0] = "wat";
    validCharArgs[1] = "twa";
    validCharArgs[2] = "awt";

    std::cout << "You passed " << argv[1] << " as the program argument. " << std::endl;
    std::cout << "Valid char* arguments are: "
        << validCharArgs[0] << ", " << validCharArgs[1] << " and " << validCharArgs[2] << ". " << std::endl;

    std::cout << "(sizeof(validCharArgs)/8)" << " = " << (sizeof(validCharArgs)/8) << std::endl;

    std::cout << "Testing with char* & traditional for loop: " << std::endl;
    for (int i = 0; i < (sizeof(validCharArgs)/8); i++)
    {
        if (validCharArgs[i] == argv[1])
        {
            std::cout << "Valid argument passed. GREAT SUCCESS!!" << std::endl;
            break;
        }

        // My attempt at getting to the end of validCharArgs[] with no valid parameters
        if (validCharArgs[i] != argv[1] && i == (sizeof(validCharArgs)/8)-1) 
        {
            std::cout << "Invalid argument passed. " << std::endl;
        }
    }

    std::cout << "Testing with auto & range for loop: " << std::endl;
    for (auto c : validCharArgs)
    {
        if (c == argv[1])
        {
            std::cout << "Valid argument passed. GREAT SUCCESS!!" << std::endl;
            break;
        }
        else if (c != argv[1] && c == validCharArgs[2]) 
        {
            std::cout << "Invalid argument passed. " << std::endl;
        }
    }

    std::cout << "Testing with std::string & range for loop: " << std::endl;
    std::string argumentAsString = argv[1];
    for (std::string s : validCharArgs)
    {
        if (s == argumentAsString)
        {
            std::cout << "Valid argument passed. GREAT SUCCESS!!" << std::endl;
            break; 
        }
        else if (s != argumentAsString && s == validCharArgs[2])
        {
            std::cout << "Invalid argument passed. " << std::endl;
        }
    }

    return 0;
}

1 Answers1

2

You cannot compare char* directly. You will end up comparing pointers, not strings. Either use strcmp(), or construct std::string/std::string_view and compare them.

Mikhail
  • 20,685
  • 7
  • 70
  • 146