Cout in loop doesn't print char by char as defined

独自空忆成欢 提交于 2019-12-02 03:04:52

问题


I've recently started learning C++ at university and decided to advance a bit at home. I had the idea of making a program that, given a piece of text, would print out such text character by character with a small delay in-between (as seen in this video SUPER.HOT chat).

I tried to recreate it using a simple procedure:

void typer(string text){

for (int i = 0; i < text.length(); i++){
    cout << text[i];
    usleep(100000);
}

But when usleep() is set under 103900, it'll start printing out two characters at a time. My intention is to print only 1 at a time but very quickly.

Any suggestions? :D


回答1:


You need to flush the stream, otherwise it will be cached

cout.flush();

http://www.cplusplus.com/reference/ostream/basic_ostream/flush/




回答2:


You need flush output

 cout << text[i] << flush;

The usleep() function returns 0 on success. On error, -1 is returned, with errno set to indicate the cause of the error.

ERRORS EINTR Interrupted by a signal; see signal(7).

EINVAL usec is not smaller than 1000000. (On systems where that is considered an error.)



来源:https://stackoverflow.com/questions/48253221/cout-in-loop-doesnt-print-char-by-char-as-defined

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!