C/C++ Arena

Step 6 of 7

Whole lines with getline

std::cin >> word reads a single word and stops at whitespace, so a line like rush b would arrive in two pieces. To read an entire line, spaces included, use std::getline:

std::string line;
std::getline(std::cin, line);

It reads everything up to the end of the line and removes the newline (unlike C's fgets, which keeps it).

Reading every line

getline returns the stream, and a stream converts to false once reading fails, which happens at the end of the input. So the standard loop is:

#include <iostream>
#include <string>

int main() {
    std::string line;
    int longest = 0;
    int count = 0;
    while (std::getline(std::cin, line)) {
        count++;
        if ((int)line.size() > longest) {
            longest = line.size();
        }
    }
    std::cout << count << " lines, longest has " << longest << " chars\n";
}
to be
or not to be
that is the question
3 lines, longest has 20 chars

Mixing >> and getline

A classic trap: after std::cin >> n; reads a number, the newline after it is still waiting in the input. A following getline reads that leftover newline and returns an empty line. The fix is to skip it first, for example with std::cin >> std::ws; (which skips whitespace) before calling getline.

Your task

Read lines until the end of input and print each one prefixed with its line number, like 1: first line. Then print total N.

Challenge 2

Read lines until the end and print the longest line (the first one on a tie) as longest: LINE. With no input at all, print no lines.

Challenge 3

The first line is a number n, followed by n lines of chat. Print the chat lines in reverse order. Careful: std::cin >> n leaves the newline after the number waiting, so the next getline would read an empty line. Skip it first with std::cin >> std::ws.

Previous: Namespaces and using Next: Where C and C++ differ