首页 > 解决方案 > 如何创建一个二维令牌数组

问题描述

我正在尝试在 C 中创建一个二维的 linux 命令令牌数组(即 ls -l | grep f*)。第一个维度迭代命令。第二个维度迭代给定命令的参数。然后每个命令及其参数将存储在数组中,该数组将传递给 execvp 执行。

例如,Tokens[i][j] 将为第 i 个命令提供第 j 个令牌。

我下面的代码不起作用。可能是因为我需要重载 + 运算符以将每个命令与其参数连接起来,而我还没有弄清楚该怎么做。但是最后一个 cout 给了我一个分段错误

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
using namespace std;

int main () {

string s;
cout << "enter commands: " << endl;
getline(cin,s);

//change string to char* for strtok

char *str=const_cast< char *>(s.c_str());


//char *delim=const_cast< char *>(d.c_str());


const int COMMAND = 5;
const int  ARGUM  = 5;
string mytokens[COMMAND][ARGUM];

char *commands[10]; // Array to hold a max of 10 commands

char *token = strtok(str, "|"); //tokenize input by separating each token      by a | symbol


int i = 0;

char *args[10] = {}; //array tp hold command args

int x, y;
for (x = 0; x < 5; x++){

         while (token != NULL)
                {
                  commands[x] = token;  // each token will be a command

                  token = strtok(NULL, " ");

         }
                for (y = 0; y < 5; y++){

args[0] = strtok(commands[y], " "); // each command will be separated from    its argument by a space
                 int tokenCounter = 0;
                         while (args[tokenCounter] != NULL)
                                {
                                tokenCounter++;

                                                                         args[tokenCounter] = strtok(NULL, " ");



                                    cout <<  commands[y] <<      args[tokenCounter] <<  endl;
                               // mytokens[y][tokenCounter] = commands[x] +  args[tokenCounter];
                         }
                }

  }

标签: c++

解决方案


推荐阅读