Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Argument is Empty or Not Same

#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.

like image 672
Mohd Shahril Avatar asked Dec 09 '22 18:12

Mohd Shahril


1 Answers

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.

like image 68
log0 Avatar answered Dec 27 '22 09:12

log0