In C++, this code is supposed to take one string, entered by the user, and separ
ID: 3833317 • Letter: I
Question
In C++, this code is supposed to take one string, entered by the user, and separate words with a space that bein with a capital letter. Right now, when running the code, if the input is "HelloThere" the output comes out as "Hello here" which means it is taking away the capital and replacing it with a space. How do I alter the code so that it keeps the capital and just adds the space to separate the words?
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
int i = 0;
int j = 0;
int length;
char input[70];
char output[70];
cout << "Input a sentence without any spaces. Make sure each new word starts with a capital letter." << endl;
cin >> input;
length = strlen(input);
output[j] = toupper(input[i]);
j = 1;
for (i = 1; j <= length; j++)
{
if (isupper(input[i]))
{
output[i] = ' ';
i++;
}
else
{
output[i] = input[i];
i++;
}
}
cout << output;
system("pause");
return 0;
}
Explanation / Answer
When we identify a certain character is upper case store the character read in the next location(i+1) of output array and store space in the current location(i) of output array. Also increment the i variable to 2 steps. That way every time there is a upper case character the current location in destination/output array contains space and the next location will have the upper case character.
Code to be changed:
if (isupper(input[i]))
{
output[i] = ' ';
output[i+1]=input[i];
i += 2;
}