Blake
Blake

Reputation: 842

Can I make a loop until `std::cin` see the `\n` character in the input buffer?

Something like this..

do{
    int x{};
    std::cin >> x;
}while(/*i want the condition mentioned here*/);

I mean, if the user input x and press Enter, I want the loop to end. Can I do that?

Upvotes: 0

Views: 75

Answers (1)

molbdnilo
molbdnilo

Reputation: 66371

The most common method is to read an entire line and then extract data from that line.

That is, a change of perspective from "read things until you encounter a newline character" to the slightly higher-level "read all the things on the line".

std::string line;
if (std::getline(std::cin, line))
{
    std::stringstream ls(line);
    int x = 0;
    while (ls >> x)
    {
        // Process x
    }
}

Upvotes: 4

Related Questions