Hello! I am trying to get only the words of a string to store into an array. For example, the string text == "cat rat Shark mouse" should cause the array newtext[4] to hold "cat, rat, Shark, mouse".
This code will not build and I cannot find the mistake I made. Thanks for any help!
I haven't looked into the logic yet, but the very first problem I could see is you didn't return something for the 'words' function. Maybe you could change the signature of 'words' to void words(...)
Hi liuyang is most likely right unless you have configured the compiler to be very forgiving (c++ shell on this site swallows it).
Also: you use already string::substr(), you could also use string::find() to get the position of the next space. You could make that way your code more readable and easier to debug.
#include <iostream>
#include <string>
#include <cassert>
#include <fstream>
usingnamespace std;
int words(string text, string newtext[])
{
int numWords = 0;
for (int pos = 0; pos < text.size(); pos++)
{
if (text[pos] != ' ')//skip all spaces up to first word
{
//get pos of space behind word
int sPos = text.find(" ", pos);
// check space position
if ( sPos > text.size() || sPos < 0)
{
sPos = text.size();
}
//insert word into array, increment number of words
newtext[numWords++] = text.substr(pos, sPos - pos);
//set new position
pos = sPos;
}
}
return numWords;
}
int main()
{
string text;
string newtext[500];
getline(cin, text);
int num = words(text, newtext);
for (int i = 0; i < num; i++)
{
cout << newtext[i] << endl;
}
}