C++: Initials from a full name

Turn a full name into its initials, however the spaces fall.

What to build

A program that reads a full name and prints its initials and its number of words.

Requirements

  • Read the whole line with getline.
  • Find where each word starts, even when there are extra spaces.
  • Print the initials as capital letters, then the number of words.

Input

One line with a name of one or more words, made of letters and spaces.

Output

The initials with no spaces, a space, and the number of words.

Constraints

The line has 1 to 200 characters and at least one letter.

Example

Input:

Nadia Rahman

Output:

NR 2

Why it works

A word begins exactly where a letter follows a space or the start of the line, so counting those positions counts the words, however many spaces lie between them.

Examples

Example 1 · Input
Nadia Rahman
Expected output
NR 2
Example 2 · Input
sheikh mohammad abdul karim
Expected output
SMAK 4

Hints

Hint 1

Read the whole line with `getline(cin, line)`, because a name has spaces in it.

Hint 2

A word starts at a letter that is either the first character or comes straight after a space.

Hint 3

`toupper` turns a letter into a capital. Print it as a `char`.

Solution

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

int main() {
    string line;
    getline(cin, line);
    string initials = "";
    int words = 0;
    for (size_t i = 0; i < line.length(); i++) {
        if (line[i] != ' ' && (i == 0 || line[i - 1] == ' ')) {
            initials += (char)toupper(line[i]);
            words++;
        }
    }
    cout << initials << " " << words << endl;
    return 0;
}

Lesson: From C to C++ →