Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C++ Beginner -- How do you take a string and split it into words? I have to take

ID: 669629 • Letter: C

Question

C++ Beginner -- How do you take a string and split it into words?

I have to take a sentence inputted by the user and set each individual word as their own string. Initially, I used an array to separate words, and had something like

//checks the number of spaces in a string

for (int i=0; i < initialString.length(); i++){

if (initialString[i] == ' '){

spacecounter++;

wordcounter++;

}

if (initialString[i] != ' '){

wordcontainer[wordcounter] += initialString[i];

}

}

Which works, but I was told I can't use arrays. Is there a way to do this without arrays, like just in a for loop?

Explanation / Answer

you can do the program using strtok.

#include<iostream.h>

#include<cstring.h>

Using namespace std;

Int main() {

Char input[50];

Cout<<”enter a string “;

Cin.getline(input,50);

Char* string;

String = strtok(input , “ . “);

While(string!=NULL) {

Cout<< string <<endl;

String = strtok(NULL, “.”);

}

}