Words of String into Array

May 18, 2016 at 5:44am
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!


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <string>
#include <cassert>
#include <fstream>

using namespace std;


int words(string text, string newtext[])
{
	for (int k = 0; k < text.size() -1; k++) 
	{
		int n = 0;
		if (text[k] != ' ')
		{
			for (int j = 1; j < text.size() - k - 1; j++)
			{
				if (text[k + j] == ' ')
				{
					newtext[n] = text.substr(k, j - 1); k = (k + j - 1); n + 1; break;
				}
				j++;
			}

		}
	}
}

int main()
{
	string text;
	string newtext[500];
	getline(cin, text);
	words(text, newtext);
	cout << newtext;
	
}
May 18, 2016 at 8:02am
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(...)
May 18, 2016 at 8:53am
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.

Example in your code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <string>
#include <cassert>
#include <fstream>

using namespace 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;
	}
}
Last edited on May 18, 2016 at 8:55am
May 18, 2016 at 9:49am
Topic archived. No new replies allowed.