vendredi 19 novembre 2021

C++ vector prints out weird elements

I'm currently in the process of learning C++ and for that I'm reading the book "C++ Primer". The book is pretty good so far and I learned a lot however I experienced weird behaviour of a vector and I'm unsure if this is right or if its a problem from my side.

The question is: "Read a sequence of words from cin and store the values a vector. After you've read all the words, process the vector and change each word to uppercase. Print the transformed elements, eight words to a line."

This is my code:

#include <iostream>
#include <vector>

using namespace::std;

int main()
{
    string input;

    vector<string> svec;

    while (cin >> input)
    {
        svec.push_back(input);

        for (auto& rows : svec)
        {
            for (auto& element : rows)
            {
                element = toupper(element);
            }
        }

        int maxWordsPerLine = 0;

        for (auto word : svec)
        {
            if (maxWordsPerLine >= 8)
            {
                cout << endl;

                cout << word;

                maxWordsPerLine = 1;
            }
            else
            {
                cout << word;

                maxWordsPerLine++;
            }
        }
    }
}

I believe it does the things described in the task but when I type in:

Hello thanks for helping I dont know whats wrong with this problem lol

The output is:

HELLOHELLOTHANKSHELLOTHANKSFORHELLOTHANKSFORHELPINGHELLOTHANKSFORHELPINGIHELLOTHANKSFORHELPINGIDONTHELLOTHANKSFORHELPINGIDONTKNOWHELLOTHANKSFORHELPINGIDONTKNOWWHATSHELLOTHANKSFORHELPINGIDONTKNOWWHATS
WRONGHELLOTHANKSFORHELPINGIDONTKNOWWHATS
WRONGWITHHELLOTHANKSFORHELPINGIDONTKNOWWHATS
WRONGWITHTHISHELLOTHANKSFORHELPINGIDONTKNOWWHATS
WRONGWITHTHISPROBLEMHELLOTHANKSFORHELPINGIDONTKNOWWHATS
WRONGWITHTHISPROBLEMLOL

I hope someone can explain me why this happens and how I can avoid it in the future. Thank you.

Aucun commentaire:

Enregistrer un commentaire