Evan Zhao
Evan Zhao

Reputation: 82

C++ won't print trailing whitespace

In my simple program to learn C++, I am asking the user their name and then greeting them.

#include <iostream>

int main() {
    std::string name;

    std::cout << "Enter your name: ";
    std::getline(std::cin, name);

    std::cout << "Hello, " << name << "!\n";
}

However, here is my result in CLion:

enter image description here

I expected the program to print out a trailing whitespace after the prompt for my name. However, it prints the space after I give the program input. I have only experienced this in CLion, but not in other IDEs. Why is this happening, and how can I fix this?

Upvotes: 4

Views: 685

Answers (1)

bolov
bolov

Reputation: 75805

You need to flush your stream:

std::cout << "Enter your name: " << std::flush;

std::cout is a buffered stream which means that while your write to it isn't immediately written to the underlying device, but it is stored in a buffer. This is done for performance reasons. std::endl has an implicit flush operation, that's why you don't notice this if you always add a std::endl before you request input. Otherwise, like you've seen that can happen.

Upvotes: 5

Related Questions