Check if Argument is Empty or Not Same

10,153

Solution 1

Everybody is giving you a different answer. And in fact everybody is right.

The signature of main, int main(int argc, char *argv[]) is inherited from C. In C strings are pointer to char. When you use operator== on them, you only compare pointer value.

The C way to compare string content is to use strcmp.

if (strcmp(argv[1], "integer") == 0){

It is safer and easier for you to do it the C++ way.

if (std::string(argv[1]) == "integer"){

This line create a temporary std::string from argv[1]. you must include string for this to work.

Finally check if argc == 2 in order to know if an argument was supplied. It is true that argv is null terminated by the standard 3.6.1 but it definitely make things clearer to check that argv is indeed equal to 2.

Solution 2

Can't use == for argv[] as it's char* type, use strcmp instead.

int main(int argc, char*argv[])
{
    if(argc == 1){
        cout << "please put something" << endl;
    }else if(strcmp(argv[1], "string") == 0){
        cout << "yeah string" << endl;
    }else if (strcmp(argv[1], "integer") == 0){
        cout << "yeah integer" << endl;
    }
  return 0;
}

Or you need to make a copy of argv[1] to std::string then you can use == operator.

Solution 3

If you want to code in C++ you can use std::string, include its header:

#include <string>

Convert the first argument to std::string and use its operator==:

std::string first = argv[1];

if(first == ""){
    cout << "please put something" << endl;
}else if(first == "string"){
    cout << "yeah string" << endl;
}else if(first == "integer"){
    cout << "yeah integer" << endl;
}

Comparison of char * to string literals doesn't make sense, if you make a std::string out of argv[1] then it's a different story, it will work as you expected.

But, you should check the number of arguments supplied to the program by the user first, it's in argc.

Solution 4

First check if argc > 1. Otherwise, you're accessing an invalid memory.

if(argc < 2){
    cout << "please put something" << endl;
}else if(argv[1] == "string"){
    cout << "yeah string" << endl;
}else if(argv[1] == "integer"){
    cout << "yeah integer" << endl;
}
Share:
10,153
Mohd Shahril
Author by

Mohd Shahril

Updated on June 04, 2022

Comments

  • Mohd Shahril
    Mohd Shahril almost 2 years
    #include <iostream>
    
    using namespace std;
    
    int main(int argc,char* argv[]){
        if(argv[1] == ""){
            cout << "please put something" << endl;
        }else if(argv[1] == "string"){
            cout << "yeah string" << endl;
        }else if(argv[1] == "integer"){
            cout << "yeah integer" << endl;
        }
    }
    

    I don't know what's wrong: I try to check if argument supplied for argv[1] is empty so it will be false and application will exit, so please tell me what is wrong in my code.