I am trying to do a command line switch with an if statement. The problem I am running into is when I am using a letter, it wont recognize it. When I use a number, no problem. I think there are a few different ways to solve this. Can anyone show me the most direct way?

Thanks.

#include <iostream>

using namespace std;

int main ( int argc, char *argv[] )
{
	if (argv[1] == "-d")
	{
		cout<<"yes, it works"<<endl;
	}
else
	{
		cout<<"no, it won't read the if statement"<<endl;
	}
}

Dani AI

Generated

The original issue is that command-line arguments come in as C-style strings (char *). Comparing those pointers with == checks addresses, not the text contents, so the test will fail even when the characters match. Also avoid reading argv[1] without first checking argc; accessing past the end of the array is undefined. is correct that strcmp fixes the content comparison, but a more modern and convenient approach is to use std::string (or std::string_view) and compare with ==.

Here is a simple, safe pattern that looks for a -d/--debug flag anywhere on the command line and prints a clear message:

#include <iostream>
#include <string>

int main(int argc, char* argv[]) {
    bool debug = false;
    for (int i = 1; i < argc; ++i) {
        std::string arg = argv[i];
        if (arg == "-d" || arg == "--debug") {
            debug = true;
        } else if (arg == "-h" || arg == "--help") {
            std::cout << "Usage: prog [-d|--debug]\n";
            return 0;
        }
    }
    std::cout << (debug ? "Debug mode enabled\n" : "Debug mode disabled\n");
    return 0;
}

Notes: always validate argc before using argv[...]. For multiple flags, values, or POSIX-style parsing use getopt/getopt_long or a library such as Boost.Program_options or CLI11. For reference on content vs pointer comparison and C++ string helpers see the strcmp docs and the std::string reference: strcmp documentation and std::string reference.

this should help, is not the perfect ways, but it works:

#include <iostream>
#include <cstring>

using namespace std;

int main ( int argc, char *argv[] )
{
    if(argc > 1){
    
	    if (strcmp(argv[1], "-d") == 0){
		        cout<<"yes, it works"<<endl;
	    }
        else{
		        cout<<"no, it won't read the if statement"<<endl;
	    }
	}
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.