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
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
it's lower case so it goes to the next element in the string
Here your condition is met (i.e. a capital letter is found), so a space is inserted. The string now becomes "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.
(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:
AdderallTen [OP] 1 points · Nov 2020
Thank you for the clear explanation! I now see what was happening