我不明白为什么下面的方法不起作用。我从多个来源了解到,这是将参数传递给函数的正确方法,并且我已经成功地打印出了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测试-std=c++11
命令行示例:
./test not not not not not 1-2 4-5 7-10
应该会导致:
2 5 10
发布于 2013-06-12 20:20:09
您的索引不正确:
for (int i = 6; i < (argc - 6); i++)
这是这样的:“从6到6从头开始。将(argc - 6)改为仅argc。
在main中,您希望读取从0到blocks.size() - 1的块。
发布于 2013-06-12 20:06:28
问题是,您为main设置了char * []
,并将其传递给一个需要const char * []
的函数。它们不匹配。
您应该从createEndBlock
中删除const
std::vector<int> createEndBlock(int argc, char *argv[])
发布于 2013-06-12 20:13:39
您有以下选项:
main
()的签名
https://stackoverflow.com/questions/17065000
复制相似问题