Home > OS >  Why does my nested loop not check the second element of vector (empty string)?
Why does my nested loop not check the second element of vector (empty string)?

Time:11-21

I'm a bit stuck on this one.. my code should stop capitalising the characters when it hits the first empty string ( text[1] ).. but when I put a breakpoint in and step forward; the third string is considered straight after the first. The second element is ignored. The exercise is to print all strings but only capitalise the first one.

#include <vector>


int main()
{
    std::vector<std::string> text = { "One, two, three-four-five. Once I caught a fish alive.", "", "Six, seven, eight-nine-ten. Then I let it go again.", "", "Why did I let it go? Because he bit my finger so.", "", "Which finger did he bite? This little finger on my right!"};

    for (auto it = text.begin(); it != text.end();   it) {
        for (auto it2 = it->begin(); it2 != it->end() && !it->empty();   it2) { //empty string in text[2] never satisfies second condition
            *it2 = toupper(*it2);
        }
        std::cout << *it << std::endl;
   };
}

Any ideas why? Thanks.

CodePudding user response:

If I understood right, you want to stop capitalizing after the first empty string, and not after the first empty character, something like:

ONE, TWO, THREE-FOUR-FIVE. ONCE I CAUGHT A FISH ALIVE.

Six, seven, eight-nine-ten. Then I let it go again.

Why did I let it go? Because he bit my finger so.

Which finger did he bite? This little finger on my right!

That could be done with only one loop and transforming the whole string:

int main()
{
    std::vector<std::string> text { "One, two, three-four-five. Once I caught a fish alive.", "", "Six, seven, eight-nine-ten. Then I let it go again.", "", "Why did I let it go? Because he bit my finger so.", "", "Which finger did he bite? This little finger on my right!"};

   for (auto it = text.begin(); it != text.end() && !it->empty();   it) {
       std::transform(it->begin(), it->end(),it->begin(), ::toupper);
   };
   
   for (auto const& str : text) {
       std::cout << str << std::endl;
   }
}
  • Related