На основании этого вопроса, который был закрыт довольно быстро:
Попытка создать программу для чтения пользовательского ввода, а затем разбить массив на отдельные слова, действительны ли все мои указатели?
Скорее, чем закрытие, я думаю, можно было бы потрудиться, чтобы помочь OP прояснить вопрос.
Я хочу токенизировать вводимые пользователем данные и сохранять токены в виде массива слов.
Я хочу использовать знаки препинания (., -) в качестве разделителя и таким образом удалить его из потока токенов.
В CI я бы использовал strtok ()
, чтобы разбить массив на токены, а затем вручную построить массив.
Примерно так:
Основная функция:
char **findwords(char *str);
int main()
{
int test;
char words[100]; //an array of chars to hold the string given by the user
char **word; //pointer to a list of words
int index = 0; //index of the current word we are printing
char c;
cout << "die monster !";
//a loop to place the charecters that the user put in into the array
do
{
c = getchar();
words[index] = c;
}
while (words[index] != '\n');
word = findwords(words);
while (word[index] != 0) //loop through the list of words until the end of the list
{
printf("%s\n", word[index]); // while the words are going through the list print them out
index ++; //move on to the next word
}
//free it from the list since it was dynamically allocated
free(word);
cin >> test;
return 0;
}
Токенизатор строки:
char **findwords(char *str)
{
int size = 20; //original size of the list
char *newword; //pointer to the new word from strok
int index = 0; //our current location in words
char **words = (char **)malloc(sizeof(char *) * (size +1)); //this is the actual list of words
/* Get the initial word, and pass in the original string we want strtok() *
* to work on. Here, we are seperating words based on spaces, commas, *
* periods, and dashes. IE, if they are found, a new word is created. */
newword = strtok(str, " ,.-");
while (newword != 0) //create a loop that goes through the string until it gets to the end
{
if (index == size)
{
//if the string is larger than the array increase the maximum size of the array
size += 10;
//resize the array
char **words = (char **)malloc(sizeof(char *) * (size +1));
}
//asign words to its proper value
words[index] = newword;
//get the next word in the string
newword = strtok(0, " ,.-");
//increment the index to get to the next word
++index;
}
words[index] = 0;
return words;
}
Приветствуются любые комментарии к приведенному выше коду.
Но, кроме того, каков наилучший способ достижения этой цели в C ++?