lundi 2 novembre 2015

use of Range Based for loops in C++

I am trying to write a program that eliminates blank spaces using a range based for loop in C++. For eg, if the input is, "what is your name?" , the output should be "Whatisyourname?" however when i run the code below, the output it gives is "Whatisyourname?me?", why is that?

 int main()
    {
        string s = "What is your name?";
        int write_index = 0;
        for (const char &c : s)
        {
                if (c != ' ')
                {
                    s[write_index++] = c;
                }
        }
        cout << s << endl;
        system("pause");
    }

Aucun commentaire:

Enregistrer un commentaire