gpt4 book ai didi

c++ - 我可以使用 std::string* argv 作为主函数参数吗?

转载 作者:行者123 更新时间:2023-12-01 14:34:00 28 4
gpt4 key购买 nike

通常我看到:

int main(int argc, char** argv)

但是我可以使用:

int main(int argc, std::string* argv)

代替?

如果不可能,我如何将 char* 转换为 std::string

PS:我正在使用 C++11

最佳答案

main 参数必须是 char** argvchar* argv[]

[basic.start.main]

2. An implementation shall not predefine the main function.This function shall not be overloaded.Its type shall have C++ language linkage and it shall have a declared return type of type int, but otherwise its type is implementation-defined.An implementation shall allow both

(2.1).a function of () returning int and

(2.2).a function of (int, pointer to pointer to char) returning int


您可以做的是使用以下方法之一转换代码中的参数:

  • 简单地分配它:
    if(argc > 1)
{
std::string str = argv[1];
}
  • 使用参数作为构造函数参数构造字符串:
    std::string str(argv[1]);
  • 使用初始化列表:
    std::string str{argv[1]};

如果您想保留参数的集合,我建议使用以下方法之一将它们保存在可变大小的容器 std::vector 中:

  • 使用 std::vector 构造函数就地构造 vector ,这里使用指向字符串数组 argv 开头和结尾的指针作为构造函数参数:
    std::vector<std::string> strs(&argv[1], &argv[argc]); //*
  • 使用初始化列表:
    std::vector<std::string> strs{&argv[1], &argv[argc]}; //*
  • 在循环中添加参数:
    std::vector<std::string> strs;

for(int i = 1; i < argc; i++) //*
strs.push_back(argv[i]);
}

*不包括argv[0]程序名。

关于c++ - 我可以使用 std::string* argv 作为主函数参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63325434/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com