0

So I was trying to write a function that prints out a string letter by letter with a 100 ms time interval between each letter. (Please don't ask me why). This is what I have written so far.

#include <iostream>
#include <time.h>
void wait(int ms){

    clock_t begin = clock(), end;
    double t;

    while(true){
        end = clock();
        t=double(end - begin) / CLOCKS_PER_SEC;
        if(t>=(double) ms/1000)
            break;
    }

    return;

}

void display_dramatically(std::string x) {
    for(int i=0;i<x.size();++i) {
        std::cout<<x[i]<<"\n";
        wait(100);
    }   
}

What's extremely weird is that it is only when I print a "\n" after x[i] that this function works. But of course then every character is also in a new line. When I remove that "\n", the program just waits for 100*(number of characters in string) milliseconds, and then prints out the whole string at once. This does not make any sense to me. Even the wait function is working perfectly. How can the presence of a newline command affect the program in this way?

  • 2
    Standard output is buffered. –  May 24 '17 at 17:26
  • If you had read the tag descriptions, it should have been obvious that `paradox` is not an appropriate tag for this question. – crashmstr May 24 '17 at 17:28
  • I am sorry for that. – Indroneil Kanungo May 24 '17 at 17:29
  • @IndroneilKanungo Welcome to Stack Overflow. Please take the time to read [The Tour](http://stackoverflow.com/tour) and refer to the material from the [Help Center](http://stackoverflow.com/help/asking) what and how you can ask here. – πάντα ῥεῖ May 24 '17 at 17:32
  • 1
    By the way, in general it's a good idea to try to avoid busy-wait loops if possible. You probably want to use `std::this_thread::sleep_for(std::chrono::milliseconds{100});`. Or, maybe use `std::this_thread::sleep_until()` with times incremented from an initial measurement, if you don't want processing time for the character output to start skewing the intervals. – Daniel Schepler May 24 '17 at 17:34
  • @DanielSchepler That works perfectly! Thank you. – Indroneil Kanungo May 24 '17 at 17:38
  • @πάνταῥεῖ thank you :) – Indroneil Kanungo May 24 '17 at 17:38

0 Answers0