Sorry I'm really new to programming and need some assistance. How would I make this happen. This is the function I currently have.
void DisplayTitle(string aTitle) {
cout << "\t" << aTitle << endl;
cout << "\t--------------\n\n";
}
How would I go about making sure that no matter which title is inputted, every character will be capitalized and the underscores will be the same amount of characters as the displayed title above.
CodePudding user response:
You can use std::setfill
combined with std::setw
from <iomanip>
as follows:
std::cout << std::setfill('-') << std::setw(title.size()) << "";
Here, you're telling the stream to use a padding character of '-'
, then a padded output size that's the length of your title, and then output an empty string. Because the string is empty, it will pad that entire area.
#include <iostream>
#include <iomanip>
#include <string>
void DisplayTitle(const std::string& title, const char* prefix = "\t")
{
std::cout << prefix << title << "\n";
std::cout << prefix << std::setfill('-') << std::setw(title.size()) << "" << "\n\n";
}
int main()
{
for (std::string title; std::getline(std::cin, title); )
{
DisplayTitle(title);
}
}
Example input:
One flew over the cuckoo's nest
The birds and the bees
Example output:
One flew over the cuckoo's nest
-------------------------------
The birds and the bees
----------------------
Here is a live demo of the above.
Oh, it seems I missed the fact your question was asking two things. You also want to capitalize the title. You can do that with std::transform
, and in fact it can even be done without modifying the string:
void DisplayTitle(const std::string& title, const char* prefix = "\t")
{
// Write title in all-caps
std::cout << prefix;
std::transform(title.begin(), title.end(),
std::ostream_iterator<char>(std::cout),
[](char c) { return std::toupper(c); });
std::cout << "\n";
// Underline title
std::cout << prefix << std::setfill('-') << std::setw(title.size()) << "" << "\n\n";
}
Here is the updated live demo with the above change.
CodePudding user response:
You can use std::transform
and to_upper
to capitalize the string.
You can use std::string
's two-parameter constructor which takes a length and a character to generate a sequence of -
of the same length as the title
Together we get:
#include <iostream>
#include <string>
#include <algorithm>
void DisplayTitle(std::string aTitle) {
std::transform(aTitle.begin(), aTitle.end(), aTitle.begin(), toupper);
std::cout << "\t" << aTitle << "\n";
std::cout << "\t" << std::string(aTitle.length(), '-') << "\n\n";
}
int main()
{
for (std::string title; std::getline(std::cin, title); )
{
DisplayTitle(title);
}
}