简体   繁体   English

如何从win32应用程序中的命令行参数获取std :: string?

[英]How to get std::string from command line arguments in win32 application?

So now I have a 所以现在我有一个

int main (int argc, char *argv[]){}

how to make it string based? 如何使它基于字符串? will int main (int argc, std::string *argv[]) be enough? int main (int argc, std::string *argv[])足够吗?

You can't change main's signature, so this is your best bet: 你不能改变主要的签名,所以这是你最好的选择:

#include <string>
#include <vector>

int main(int argc, char* argv[])
{
    std::vector<std::string> params(argv, argv+argc);
    // ...
    return 0;
}

If you want to create a string out of the input parameters passed, you can also add character pointers to create a string yourself 如果要从传递的输入参数中创建字符串,还可以添加字符指针以自行创建字符串

#include <iostream>
#include <string>
using namespace std;

int main(int argc, char* argv[])
{

string passedValue;
for(int i = 1; i < argc; i++)
 passedValue += argv[i];
    // ...
    return 0;
}

You can't do it that way, as the main function is declared explicitly as it is as an entry point. 你不能那样做,因为main函数是明确声明的,因为它是一个入口点。 Note that the CRT knows nothing about STL so would barf anyway. 请注意,CRT对STL一无所知,所以无论如何都要barf。 Try: 尝试:

#include <string>
#include <vector>

int main(int argc, char* argv[])
{
    std::vector<std::string> args;
    for(int i(0); i < argc; ++i)
        args.push_back(argv[i]);

    // ...

    return(0);
}; // eo main

That would be non-standard because the Standard in 3.6.1 says 这将是非标准的,因为3.6.1的标准说

An implementation shall not predefine the main function. 实现不应预定义主函数。 This function shall not be overloaded. 此功能不应过载。 It shall have a return type of type int , but otherwise its type is implementation-defined. 它应该具有int类型的返回类型 ,否则其类型是实现定义的。 All implementations shall allow both of the following definitions of main: 所有实现都应允许以下两个主要定义:

int main() { /* ... */ }

and

int main(int argc, char* argv[]) { /* ... */ }

No. That is not allowed. 不,那是不允许的。 If present, it is mandated to be char *argv[]. 如果存在,则强制要求为char * argv []。

BTW, in C++ main should always be declared to return 'int' 顺便说一下,在C ++ main中应该总是声明为返回'int'

main receives char*. main接收char *。 you will have to put the argv array into std::strings yourself. 你必须自己把argv数组放到std :: strings中。

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

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