C++, lesson 8
std::string (from <string>) is C++'s text type. Unlike a C string, it knows its own length,
grows as needed, and frees its memory automatically. You can copy it with =, compare it with
== and <, and join strings with +.
std::cin >> word stops at whitespace. To read a full line, spaces and all, use
std::getline. It returns the stream, so it works as a loop condition, and it throws away the
newline for you:
One trap: after std::cin >> n, the newline that followed the number is still waiting, so the
next returns an empty string. Write first to skip that leftover
whitespace.
2 exercises to try what you just read.
getlinestd::cin >> std::ws;| Operation | Result |
|---|---|
s.size() or s.length() | number of characters |
s[i] | character at index i (from 0) |
s.find("abc") | index of the first match, or std::string::npos |
s.substr(pos, count) | a new string of up to count characters from pos |
s.empty() | true if there are no characters |
A std::string is mutable. Loop with a reference to change each character in place.
<cctype> provides std::toupper, std::tolower, std::isalpha, std::isdigit and
std::isspace. They expect an unsigned char value, so cast first to stay safe with non-English
letters:
To build a new string, start empty and push_back characters or += pieces onto it.
std::istringstream (from <sstream>) lets you read from a string exactly as you read from
std::cin. It is the easiest way to split a line into words:
Its sibling std::ostringstream builds a string with <<, which is handy for formatting.
C++17's std::string_view (from <string_view>) is a lightweight, read-only window onto
characters owned by someone else. It is a good parameter type for functions that only read
text, because it accepts std::string, string literals and slices without copying. Just never
keep a string_view after the text it points to has gone away.
A palindrome reads the same forwards and backwards once you ignore case and everything that is
not a letter. Read lines until the input ends. For each line print yes if it is a palindrome
and no otherwise. A line with no letters at all counts as a palindrome.
Plan: build a cleaned string of lowercase letters, then compare it with its reverse
(std::string(clean.rbegin(), clean.rend()) builds the reverse).
Time to combine everything so far. Read text until the input ends and print:
Lines: <n>, the number of linesWords: <n>, where a word is any run of non-space charactersLongest: <word>, the longest word (the first one if several tie), or none if there are no wordsAverage length: <x>, the average word length with two decimals (0.00 if there are no words)Initials: <letters>, the first character of every word, in upper case, joined together
(empty if there are no words)Use std::getline for lines and an std::istringstream to split each line into words. Keep the
logic in small functions if main gets long.
std::string first{"Ada"};
std::string full{first + " Lovelace"};
full += "!";
std::cout << full << " has " << full.size() << " characters\n"; // 13std::string line;
while (std::getline(std::cin, line)) {
std::cout << "[" << line << "]\n";
}std::string email{"ada@example.com"};
if (auto at = email.find('@'); at != std::string::npos) {
std::string user{email.substr(0, at)}; // "ada"
std::string domain{email.substr(at + 1)}; // "example.com"
}for (char& c : text) {
c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
}std::istringstream words{"the quick brown fox"};
std::string w;
while (words >> w) {
std::cout << w << '\n'; // four words; extra spaces are skipped
}Input:
Never odd or even
Hello
A man, a plan, a canal: Panama!
Output:
yes
no
yesInput:
the quick brown fox
jumps over the lazy dog
Output:
Lines: 2
Words: 9
Longest: quick
Average length: 3.89
Initials: TQBFJOTLD