c++ - 如何创建一个二维令牌数组
问题描述
我正在尝试在 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];
}
}
}
解决方案
推荐阅读
- css - 在 Mozilla 中使用抗锯齿和灰度时属性值无效
- node.js - 在 Express 中将 ReactJS 生产构建部署为 HTTPS
- android - MediaPlayer setDataSource 失败,defaultUri 的 status=0x80000000
- azure - 从机器人框架中的状态数据中恢复对话数据
- nginx - 如何使用 nginx 在 https 模式下运行 odoo?
- java - Android java.lang.ClassCastException: android.view.AbsSavedState$1 无法转换为 android.widget.CompoundButton$SavedState
- android - 如何将 OpenSL ES 库作为依赖项添加到项目中?
- c++ - Resharper C++ 和 Plog 记录器
- android - Spotify API 不会创建私人播放列表
- wordpress - 如何仅使用 .htaccess 在 1and1 上托管的 WordPress 网站上的所有页面上强制使用 HTTPS