Tidy up the capitals in a line.
What to build
A program that splits a line and rebuilds it.
Requirements
- Read a whole line.
- Make the first letter of each word upper case, and every other letter lower case.
- Print the words separated by single spaces.
Input
One line of words.
Output
One line.
Constraints
The line has from 1 to 200 characters. Words contain only letters.
Example
Input:
hello world
Output:
Hello World
Why it works
A string stream handles the splitting, and any amount of space between words is skipped automatically.
Examples
Example 1 · Input
hello world
Expected output
Hello World
Example 2 · Input
the QUICK brown FOX
Expected output
The Quick Brown Fox
Hints
Hint 1
Use istringstream to get the words.
Hint 2
Make the whole word lower case, then the first letter upper case.
Hint 3
Print a space only before words after the first.
Solution
Show one correct solution (try it yourself first)
#include <cctype>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
string line, word;
getline(cin, line);
istringstream in(line);
bool first = true;
while (in >> word) {
for (char& c : word) {
c = static_cast<char>(tolower(c));
}
word[0] = static_cast<char>(toupper(word[0]));
if (!first) cout << " ";
cout << word;
first = false;
}
cout << endl;
return 0;
}