3

我不明白为什么以下不起作用。我从几个来源读到这是将参数传递给函数的正确方法,并且我已经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
4

4 回答 4

2

您的索引不正确:

for (int i = 6; i < (argc - 6); i++)

读作“从 6 到 6 结束。将 (argc - 6) 更改为 argc。

主要是,您想读取从 0 到 blocks.size() - 1 的块。

于 2013-06-12T12:20:09.063 回答
0

问题是您拥有char * []main,并将其传递给期望const char * []. 他们不匹配。

你应该constcreateEndBlock

std::vector<int> createEndBlock(int argc, char *argv[])
于 2013-06-12T12:06:27.543 回答
0

您有以下选择:

  • 从createEndBlock()的签名中删除 const
  • 将 const 添加到main()的签名中
  • 调用createEndBlock()时使用const_cast<>添加constness
于 2013-06-12T12:13:38.503 回答
0

您的blocks[i]语句可能具有传递给它们的无效索引。再次查看 createEndBlock 的内部循环。您检查特定条件,仅在满足该条件时才添加新块。那么,如果测试在 i=0 时失败然后在 i=1 时通过,会发生什么?很简单,然后您尝试访问 blocks[ 1 ],但它只有一个元素 blocks[ 0 ]。结果?繁荣!

于 2013-06-12T12:18:15.993 回答