Break out of a while loop?

closed account (EwCjE3v7)
I have this excercise:
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.


And I don`t know how to do it with a getline so Here is what I did instead

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <vector>
using std::cout; using std::cin; using std::endl;
using std::vector; using std::string;

int main()
{
    string input;
    vector<string> container;

    while (cin >> input) {
        container.push_back(input);
    }
    unsigned counter = 0;
    for (auto &c : container[counter]) {
        c = toupper(c);
        ++counter;
    }
    counter = 0;
    for (auto &word : container) {
        cout << word << " ";
        ++counter;
        if (counter > 8) {
            cout << endl;
        }
    }

    return 0;
}


But how do i break out of the while loop until I get a certain about of words?
To explicitly break out of ANY loop use break;
closed account (EwCjE3v7)
But how can I get a certain amount of inputs till I break?
Becuz if i just write break then its just like writing if (..) ...

Oh stupid me, i think i got it
Last edited on
Use a for loop. Its better.

For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<string> names;
    
    for(int i = 1; i<=5; i++) //Get 5 inputs till the loop exits
    {
        cout << "Enter your name plz: ";
        string usrName;
        cin >> usrName;
        names.push_back(usrName);
    }
    
    return 0;
}


If you want a while loop, make a counter then in the condition check the counter and increment it at the end of the loop.

Here is an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<string> names;
    int counter = 1; //Set a counter
    while(counter <= 5) //Check the counter
    {
        cout << "Enter your name plz: ";
        string usrName;
        cin >> usrName;
        names.push_back(usrName);
        counter++; //Increment the counter
    }
    
    return 0;
}
Last edited on
closed account (EwCjE3v7)
Yep, got you. Thanks.
A bit of information:

Any for loop can be written as a while loop. If a while loop can be written as a for loop, it is common practice to write it as a for loop for easy readability (and just a different way of organizing/understanding the programming logic).
Topic archived. No new replies allowed.