2

I'm trying to create a program where text is outputted to the console with a character by character delay. (Also, I'm pretty new to this, so I don't have a very great understanding on how cout works.)

int main() {
  std::cout << "L";
  waitms(1000); //function that pauses 1 second.
  std::cout << "l";
  waitms(1000);
  std::cout << "a";
  waitms(1000);
  std::cout << "m";
  waitms(1000);
  std::cout << "a";
}

When this code is ran, the console waits for four seconds and then prints Llama to the console.

This can work if you add \n characters to the end of the strings, but it produces an undesirable output.

Code: (waits four seconds) Llama

Undesired: L (does wait, but adds newlines.)
           l
           a
           m
           a

Desired: L (wait 1 second) l (wait) a (wait) m (wait) a
Llama

Is there any way to pop the stream without a newline?

kalkr
  • 27
  • 5

2 Answers2

7

You need to flush your output, such as with std::flush:

std::cout << "L" << std::flush;
waitms(1000);
std::cout << "l" << std::flush;
// ... etc ...

std::cout usually buffers console output. Printing a newline via '\n' usually flushes the output, and std::endl always flushes. This is why you don't normally notice. But if you want to print things on one line with a delay, you need to flush the console output by hand.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
0

I figured out something similar, but using the #include <windows.h> header. But I'm looking for a faster way.. is there a function where you can write an entire string and have that function chop it up for you so you don't have to be writting all this code in between letters? I know there is, but I can't figure it out by myself... this is what I wrote:

cout << "R"; Sleep(300); cout << "E"; Sleep(300); cout << "C"; Sleep(300); cout << "U"; Sleep(300); cout << "R"; Sleep(300); cout << "S"; Sleep(300); cout << "I"; Sleep(300); cout << "V"; Sleep(300); cout << "E           "; Sleep(300); cout << "F"; Sleep(300); cout << "U"; Sleep(300); cout << "N"; Sleep(300); cout << "C"; Sleep(300); cout << "T"; Sleep(300); cout << "I"; Sleep(300); cout << "O"; Sleep(300); cout << "N" << endl;
Sleep(300);
cout << "***********************************************************";
Sleep(800); cout << endl << "What "; Sleep(800); cout << "Is "; Sleep(800); cout << "It?" << endl;
Sleep(2000);
cout << "      It is a function that calls itself. " << endl; Sleep(500); cout << "            To avoid having this function run indefinitely, you must inclue a termination condition" << endl << endl;
Sleep(1000); 
cout << "               (kinda reminds me of a for loop, doesn't it?)" << endl;