C ++函数将字符串解析为标记

时间:2015-02-07 05:47:47

标签: c++ arrays string parsing pointers

我正在尝试构建一个函数,该函数接收一个c字符串和一个指向字符指针数组的指针,并且应该返回在将每个标记放入指向字符指针的指针数组时找到的标记数。例如,如果我传入字符串ls -l file,它应该放入一个c字符串数组,每行包含一行(args[1] = "I\0", args[2] = "am\0", args[3] = "the\0", args[4] = "test\0", args[5] = "string\0")。谢谢你的帮助!

这是我到目前为止所做的,但我的内存访问违规行为:

#include <iostream>
using namespace std;

int MakeArg(char [], char** []);

int main()
{
    char str[] = "I am the test string";
    char** argv;
    int argc;

    argc = MakeArg(str, &argv);

    cin.ignore();
    cout << "\nPress enter to quit.";
    cin.ignore();

    return 0;
}

int MakeArg(char s[], char** args[])
{
    int word = 1;   

    for (int i = 0; s[i] != '\0'; i++) //iterates through every character in s
    {
        *args[word][i] = s[i]; //adds each character to word
        if (s[i] == ' ') //when a space is found
        {
            *args[word][i] = '\0'; //it replaces it with a nullbyte in args
            word++; //and moves on to the next word
        }
    }

    return word; //returns number of words
}

0 个答案:

没有答案