我不明白为什么以下不起作用。我从几个来源读到这是将参数传递给函数的正确方法,并且我已经argv
成功打印了内容。
我们的想法是从命令行调用程序,它将使用高于 5 的所有参数(因此应忽略应用程序名称 + 5 个其他参数)。还有什么问题?
#include <iostream>
#include <vector>
#include <regex>
#include <sstream>
using namespace std;
std::vector<int> createEndBlock(int argc, const char *argv[])
{
std::vector<int> blocks;
for (int i = 6; i < (argc - 6); i++)
{
string str = argv[i];
for (int j = 0; j < str.size(); j++)
{
if (str[j] == '-') {
blocks.push_back(atoi(str.substr(j+1).c_str()));
cout<<blocks[i]<<endl;
}
}
}
return blocks;
}
int main(int argc, char* argv[]) {
std::vector<int> blocks;
blocks = createEndBlock(argc, argv);
for (int i = 6; i < 7; i++)
{
cout<<blocks[i]<<endl;
}
return 0;
}
我收到以下错误:
test.cpp: In function ‘int main(int, char**)’:
test.cpp:38:37: error: invalid conversion from ‘char**’ to ‘const char**’
[-fpermissive]
test.cpp:19:18: error: initializing argument 2 of ‘std::vector<int>
createEndBlock(int, const char**)’ [-fpermissive]
编译:g++ test.cpp -o test -std=c++11
命令行示例:
./test not not not not not 1-2 4-5 7-10
应该导致:
2 5 10