Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ won't print trailing whitespace

Tags:

c++

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?

like image 347
Evan Zhao Avatar asked Oct 28 '25 15:10

Evan Zhao


1 Answers

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.

like image 160
bolov Avatar answered Oct 31 '25 07:10

bolov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!