简体   繁体   English

将值传递给main(int,char **)

[英]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. 我有一个显示ascii值和字母的程序,但是现在我修改了该程序以仅显示我要查找的西班牙语字符。 The program is called, yes, you got it, "ascii". 该程序称为,是的,您知道它为“ ascii”。 What the user has to do is type C:>ascii or C:>ascii all to display all the ascii characters. 用户要做的是键入C:>asciiC:>ascii all来显示所有ascii字符。 To display only the Spanish characters the user must type C:>ascii es . 要仅显示西班牙语字符,用户必须输入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. 但是程序总是在else条件关键字中跳转到ascii_es方法。 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 . 您可以通过将其中一个参数更改为std::string或使用strcmp(...) == 0来解决此问题。
  2. argv[0] is the name of your program. argv[0]是您的程序的名称。 Use argv[1] for the first argument. 第一个参数使用argv[1]
  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. 如果没有,则访问argv[1]将导致未定义的行为。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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