Array and String

The purpose of the program is to take the sentence in the "sentence string" and capitalize the first letter in the beginning of each sentence. The program can successfully capitalize "hello", but not the other letters. The problem seems to be coming from the for loop and the sentenceArray.

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
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
{
	string sentence = "hello user. today is a good day. hope yours is too."; //51 
	char sentenceArray[51];
	char period = '.';

	for(int i = 0; i < sentence.size(); i++)
	{
		sentenceArray[i] = sentence[i];
		if (sentenceArray[i] == sentence[0])
		{
		sentenceArray[0] = toupper(sentenceArray[0]);
		}
		if (sentenceArray[i] == '.' && (i + 2) < sentence.size())
		{
			sentenceArray[i + 2] = toupper(sentenceArray[i+2]);
		}
	}


	for (int i = 0; i < 51; i++)
		cout << sentenceArray[i] << endl;
	
	system("pause");
	return 0;
}
At line 21, you make sentenceArray[i + 2] upper-case. However, that element of sentenceArray hasn't even been given a value yet, so it's a meaningless thing to do!

Then, 2 iterations later, you overwrite it on line 14 with the original letter from sentence[i].

Also, line 14 will make every occurrence of 'h' upper-case, regardless of where it appears in the string. Or at least, it would if it wasn't for the first problem.

Last edited on
Topic archived. No new replies allowed.