简体   繁体   English

命令行 Arguments 带“-”前缀

[英]Command Line Arguments With “-” Prefix

I'm trying to write a program which I'll be able to start with custom arguments.我正在尝试编写一个程序,我可以从自定义 arguments 开始。 Like in this example "program.exe -width 1920 -height 1080".就像在这个例子中“program.exe -width 1920 -height 1080”一样。 I wrote a simple code, which should work.我写了一个简单的代码,它应该可以工作。

#include <iostream>

int main(int argc, char* argv[])
{
    for (int i = 1; i < argc; i++)
    {
        if (argv[i] == "-width")
        {
            std::cout << "Width: " << argv[++i] << "\n";
        }
        else if (argv[i] == "-height")
        {
            std::cout << "Height: " << argv[++i] << "\n";
        }
    }

    return 0;
}

And this program doesn't work.而且这个程序不起作用。 It's not displaying anything.它没有显示任何东西。 I also tried checking this code line by line with debugger, but when argv[i] == "-width" it just skips it.我还尝试使用调试器逐行检查此代码,但是当argv[i] == "-width"它只是跳过它。

Is there a way to fix it or there are just some other methods of doing this?有没有办法解决它,或者只有其他一些方法可以做到这一点?

You are comparing pointers, not strings.您正在比较指针,而不是字符串。 To compare strings via == , you should use std::string .要通过==比较字符串,您应该使用std::string

Also you should check if the elements argv[++i] exists.您还应该检查元素argv[++i]是否存在。

#include <iostream>
#include <string>

int main(int argc, char* argv[])
{
    for (int i = 1; i < argc; i++)
    {
        if (argv[i] == std::string("-width") && i + 1 < argc)
        {
            std::cout << "Width: " << argv[++i] << "\n";
        }
        else if (argv[i] == std::string("-height") && i + 1 < argc)
        {
            std::cout << "Height: " << argv[++i] << "\n";
        }
    }

    return 0;
}

You can also use the s suffix也可以使用 s 后缀

cout << ("wilson" == "wilson"s) << endl;

output: output:

1

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

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