2

此方法接受一个向量(inputVector,成员变量)并将其拆分为 char*[]。每当你遇到一个“;” 在向量中,打印出存储在 args 中的最后一组 char*s。即使向量大小为 14,循环也会在第 5 个循环中退出。

矢量数据(换行符分隔项目):
/bin/echo
killroy

这里;
;
xyzzy
;
不存在的程序

/bin/真

/bin/假

void TrivialShell::splitArguments() {

    char* args[MAX_ARGS];

    int inputVectorIdx = 0;
    int currentArgsIdx = 0;
    int startingArgsIdx = 0;

    while (inputVectorIdx < inputVector.size()) {

        if (inputVector[inputVectorIdx] == ";") {
            for (int k = startingArgsIdx; k <= currentArgsIdx; k++) {
                cout << args[k];
            }
            startingArgsIdx = currentArgsIdx + 1;
        }

        else {
            args[currentArgsIdx] = 
                const_cast<char*>(inputVector[inputVectorIdx].c_str());
        }

        inputVectorIdx++;
        currentArgsIdx++;
    }
}
4

2 回答 2

1
for (int k = startingArgsIdx; k < currentArgsIdx; k++) {
 //                             ^^
                cout << args[k];
}

You are trying to print one too much. You haven't said it but I am sure it doesn't just skip the loop but exits the program.

于 2013-04-11T23:51:26.753 回答
1

你有一个错误。当你进入你的循环

if (inputVector[inputVectorIdx] == ";") {
            for (int k = startingArgsIdx; k <= currentArgsIdx; k++) {
                cout << args[k];
            }
            startingArgsIdx = currentArgsIdx + 1;
        }

您的索引迭代器 currentArgsIdx 大于您在 array 中的实际数据大小argscout<<args[3]因此,当那里已经有一些垃圾时,您正在这样做。这是因为您在 while 循环结束时 ++ 您的索引:

inputVectorIdx++;
currentArgsIdx++;

以不同的方式安排它或将条件更改为:

for (int k = startingArgsIdx; k < currentArgsIdx; k++) {
                               ^^^
                cout << args[k];
            }
于 2013-04-12T00:03:03.867 回答