So I have this assignment for a class where I am supposed to modify a C-String sentence, yes the one from the 80s, and then return that to the user. I am having some trouble with getting it to work properly and I need help making it run. The sentence should start with an uppercase letter and then the rest should be lowercase. It should also delete any extra space that isn't needed- (i.e. "Hello World" becomes "Hello world.". I also need to add a period to the very end of the sentence. Right now I can't get the extra spaces to be removed, here is what I have so far:
int main()
{
char userString[101];
cout << "Please enter a sentence to be edited: ";
cin.getline(userString, 100);
for (int i = 0; i < 102; i++)
{
userString[i] = tolower(userString[i]);
if ((userString[i] == ' '))
{
if (userString[i+1] == ' ')
{
//I NEED HELP HERE
}
}
}
userString[0] = toupper(userString[0]);
cout << userString << endl;
Line 8 is incorrect. Valid indices for an array of size 101 are 0 through 100, and you also make no effort to stop the loop when the end of your C-string is found.
You should use two indexes into userString. One to keep track of where you are writing to it and one to keep track of where you are reading from it. If you're skipping space, obviously those two places are going to be different. Also, you must address the issue of extra spaces before you write it back to the string, so line 10 should be after (and dependent on) the conditions you are attempting to address on lines 11/13.
So I need to change my for loop to go to only 101? Then I need to move line 10 to after removing the extra spaces? I just thought that if I had made everything lowercase from the get go, it wouldn't have mattered. I will do that. However, can you give me a little more clarification about the two indexes? Maybe an example? Thank you!