In my code,
asUpper creates a new uppercase string from the parameter and returns it. It could've been written:
1 2 3 4 5 6 7 8
|
std::string asUpper(const std::string& s)
{
// for each character in s, add the uppercase version to result.
std::string result ;
for ( auto it = s.begin(); it != s.end(); ++it )
result += std::toupper(*it) ;
return result ;
}
|
Now, in main, the
paragraphs variable is meant to store, in each element, a paragraph. It isn't a collection of individual words, or individual lines. Each element will be a full paragraph.
The
while (std::cin)
should be fairly obvious. We're going until input fails and puts
std::cin into an error state, just like your original code.
input is where we store each individual line as it is extracted from the input stream.
paragraph is the paragraph we build with the individual lines. This could be done without the paragraph variable, but I thought this would be more clear.
That brings us to:
1 2
|
while ( std::getline(std::cin, input) && input.length() )
paragraph += (input + '\n') ;
|
std::getline extracts a line of text delimited by a newline and discards the newline. Like the extraction operator(>>), std::getline returns a reference to the
std::getline returns a reference to the
std::istream that is fed to it and reflects it's error state which is what we're checking in the while condition - while the input succeeded and the input didn't consist solely of a newline.
So if the input is
"This is a line of text.\nAnd this is another one.\n\n" the first string extracted from the input stream is:
"This is a line of text." Since the newline is discarded, it is added back to the input variable to preserve the original formatting and then the resulting string is appended to the paragraph variable. The second extraction yields the string
"And this is another one." And the third extraction yields an empty string, because all that's left in the input stream is "\n", which breaks us out of the inner while loop.
Now, the paragraph string holds an entire paragraph, so we simply add it to the
vector of paragraphs, and the process begins again at the top of the loop for any additional input remaining in the input stream.
Finally,
paragraphs is iterated through.
asUpper is used to output the first paragraph as an uppercase string. A newline is inserted into the output stream after each paragraph to maintain the original formatting, because the empty lines were discarded when input was processed.