C++: Tidy a list of words

Change a list of words in place, and report what changed.

What to build

A function that changes each word of a list, through references at two levels.

Requirements

  • Write int tidy(vector<string>& words), which makes every word lower case and returns how many words actually changed.
  • Write void show(const vector<string>& words), which prints the words separated by single spaces.
  • Print the number changed, then the words.

Input

The first line has n. The second line has n words.

Output

Two lines.

Constraints

n is from 1 to 100. Words are letters only.

Example

Input:

3
Hello world BYE

Output:

2
hello world bye

Why it works

A reference in the outer loop reaches each word, and one in the inner loop reaches each character. With a copy at either level, the changes would be lost.

Examples

Example 1 · Input
3
Hello world BYE
Expected output
2
hello world bye
Example 2 · Input
1
a
Expected output
0
a

Hints

Hint 1

Take the vector by reference, and use for (string& w : words).

Hint 2

Inside, use for (char& c : w).

Hint 3

tolower(c) gives the lower-case form of a character.

Solution

Show one correct solution (try it yourself first)
#include <cctype>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int tidy(vector<string>& words) {
    int changed = 0;
    for (string& w : words) {
        bool different = false;
        for (char& c : w) {
            char lower = static_cast<char>(tolower(c));
            if (lower != c) {
                different = true;
                c = lower;
            }
        }
        if (different) changed++;
    }
    return changed;
}

void show(const vector<string>& words) {
    for (const string& w : words) cout << w << " ";
    cout << endl;
}

int main() {
    int n;
    cin >> n;
    vector<string> words(n);
    for (int i = 0; i < n; i++) cin >> words[i];
    cout << tidy(words) << endl;
    show(words);
    return 0;
}

Lesson: References →