简体   繁体   中英

Passing values to main(int, char**)

I have a program that displays ascii values and letter, but now I have modify the program to display only the Spanish characters I am looking for. The program is called, yes, you got it, "ascii". What the user has to do is type C:>ascii or C:>ascii all to display all the ascii characters. To display only the Spanish characters the user must type C:>ascii es .

For this I have written this simple program

int main(int argc, char** argv) {
    if(argv[0] == "es"){
        abc::ascii_es();        
    }
    if(argv[0] == "all"){
        abc::ascii_all();
    }
    else
        abc::ascii_es();

    return 0;
}

but the program always jumps to the ascii_es method in the else condition keyword. What am I doing wrong?

Issues:

  1. You're not comparing strings, you're comparing pointers. You can fix this by changing one of the arguments to std::string or by using strcmp(...) == 0 .
  2. argv[0] is the name of your program. Use argv[1] for the first argument.
  3. You're not checking that there are arguments to the program. And if there are none, then accessing argv[1] will cause undefined behavior.

Some working code:

#include <string>

int main(int argc, char** argv) {
    if (argc < 2)
        abc::ascii_es();
    else if (argv[1] == std::string("es"))
        abc::ascii_es();        
    else if (argv[1] == std::string("all"))
        abc::ascii_all();
    else
        abc::ascii_es();
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM