The output vector of eight words in the string

Hey all, sorry for my French)))

I have a problem, learn from the book, there is a challenge:
type the words translate to upper case, fill the vector and display of eight words in the string. Actually all did except the last (eight words per line). Help please. :)

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
#include <iostream>
#include <string>
#include <vector>
#include <cctype>

using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::vector;

int main()
{
	cout << "Enter words:" << endl;
	vector<string> vsstr;
	string sstr;

	while (cin >> sstr) {
		for (auto &i : sstr)
			i = toupper(i);
		vsstr.push_back(sstr);
	}
	for (auto j : vsstr)
		cout << j << " ";
	cout << endl;
	return 0;
}
Last edited on
Instead of using the range-based for loop on line 23, use one with a counter so you can output '\n' every 8th word instead of always a space. In other words, something like:
23
24
for (unsigned int i = 0; i < vsstr.size(); ++i)
  // ... 
One way is that you can add a word counter in the for loop. When that counter reaches 8, output a '\n'.

1
2
3
4
5
6
7
8
9
10
11
12
int word_counter = 0;
for (auto j : vsstr)
{
    cout << j << " ";
    word_counter++;
    if ( word_counter == 8 )
    {
         cout << "\n";
         word_counter = 0;
    }
}
cout << endl;

Zhuge Thank you, after I wrote the first post, all made in the likeness as you suggested.

abhishekm71 And thank you, everything was very simple, it's a pity that I had not solved it.

Tell me, do you understand what I write? partially use translator
Topic archived. No new replies allowed.