Making a string array of Char array

This is still a work in progress, but my question is this-> I am trying to make a string array that stores each char in a sentence until a whitespace or \0. Currently, it seems like its creating an new element of the array for every letter(?). Any suggestions on how to fix this code.

(ignore the bits about piglatin, havent gotten to that yet)
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
48
49
50
51
52
53
54
 // stores individual word and its piglatin translation
struct Word{
	string english;
	string piglatin;
};


int main()
{

	Word wordArr[75] {};
	char chars[250] {'\0'};
	// ask user to enter a string using getline
	cout << "Please enter a sentence to be converted into piglatin: ";
	cin.getline (chars, 250);

	// calculate how many words are in string and make "Word" array of same size

	int wordCount = 0;

	for (int i = 0; chars[i] != '\0'; i++)
	{

		int wordSize = 0;

		// convert to lowercase
		if (chars[i] != ' ')
		{
			tolower(chars[i]);
			wordSize++;
		}


		// make string of english word
		
			string tempString(chars, i, wordSize);
			wordArr[wordCount].english = tempString;
		
	

		
		cout << wordArr[wordCount].english;
		cout << wordCount;

		wordSize = 0;
	}

	// store the separate words into structure Word
	

	// strcat() <- adds ay to end

	return 0;
}
Line 29 needs to be:
 
  chars[i] = tolower(chars[i]);

because tolower only returns the converted character, it doesn't write to the passed argument.

Also "wordCount" never advances, it stays at 0, over-writing the first/0-th element again and again. You prolly meant add "++wordCount" at the end of your for-loop. You should also subsequently add a check for wordCount reaching or exceeding the size of your word array (ie, 75), and breaking the loop if so. Just to be sure you don't do an out-of-bounds access.

Your string constructor on line 36 is not right either. I would replace lines 36 & 37 with:
 
wordArr[wordCount].english = string( &chars[i], wordSize );

That way you use the "string(const char* str, size_t length)" c-tor that you intended to use and avoid creating tempString at the same time.
Last edited on
Topic archived. No new replies allowed.