C++ Using insert in a for loop?

I am trying to separate strings if they have a capital letter such as JohnSmith becomes John Smith for a homework problem without the use of other libraries and tried to use a for loop to find capital letters and then using .insert() to put a space within the string but when I run the program it keeps accepting the user input for the string but does not print anything out. What is wrong with my approach?

4 comments · 92% upvoted · other discussions

comments

stkfig

The bolded letter is the letter that is currently being checked within an interation of your for loop. This should hopefully illustrate the issue:

The for loop (as shown in your screenshot) starts at index 1

PeterParker

it's lower case so it goes to the next element in the string

PeterParker

PeterParker

PeterParker

PeterParker

Here your condition is met (i.e. a capital letter is found), so a space is inserted. The string now becomes "Peter Parker"

Peter Parker

Again the condition is met, since the capital P is now one index further along in the array since a space has been inserted.

Peter Parker

Peter Parker

Peter Parker

Peter Parker

(This doesn't show up using reddit's formatting, so look at this screenshot for a clearer demonstration https://imgur.com/2AJ3KCz )

One easy way to correct this, you could increment your count when the condition is met:

for (int i = 1; i < str1.size(); i++){  
    if (str1[i] >= 'A' && str1[i] <= 'Z') {
        str1.insert(i, " ");
        i++;
    }
}
AdderallTen [OP]

Thank you for the clear explanation! I now see what was happening

[deleted]

[removed]

AdderallTen [OP]

Yes I have but the only examples I found was using insert without any loop.

Here is the link to my code https://imgur.com/a/Rz3sRP1