有和没有换行字符的睡眠行为
Behavior of sleep with and without new line character
考虑下面的代码,其中有两个测试区域
在第一次测试中(测试1::不加新线),程序按规定休眠10秒(5*2)。但是所有的5 *都是only after the 10 seconds finished.
在第二次测试中(测试2::带新线),程序休眠10秒(5*2)。但是# s是在每两秒钟睡眠后打印的。
这背后的逻辑是什么?
Compiler:g++
platform:UNIX
,
我研究睡眠是不是标准库的一部分?我们需要使用pthread.h
如果不包含pthread.h
#include<iostream>
int main()
{
using namespace std;
// Test 1 :: without new line
for(int i=0;i<5;i++)
{
sleep(2);
cout<<"*";
}
cout<<"n";
// Test 2 :: with new line
for(int i=0;i<5;i++)
{
sleep(2);
cout<<"#n";
}
return 0;
}
当连接到终端时,std::cout
是行缓冲的。您需要一个显式的cout << flush;
来使每个*
单独出现。
关于您的第一个问题,cout不会立即冲洗。它执行的时间取决于许多因素,但在这种情况下,它似乎只在看到换行符时才刷新。如果要强制刷新,可以使用
cout << flush;
// or
cout.flush();
关于pthreads:很可能你的编译器在默认情况下只包含了所需的头文件
相关文章:
- 防止控制台在通道字符(在 c++ 中)中输入空格(即空格、制表符和换行符)
- 一次读取一个字符的文件,直到使用 read(2) 和 write(2) 换行符
- 读取文件内容时未定义的字符,文件末尾没有换行符
- 每隔n个字符打印一行换行符
- 如果字符串是从字符类型中给定的,则该字符串是否可以包含换行符
- 便携式字符换行符
- 如何从字符数组中去除换行符
- 使用 getchar() 输入字符的最有效方法,就像 cin 中没有换行符和空格字符一样C++
- C++:抓取文件的每个字符,忽略换行符和空格
- 检查字符是否为换行符
- 基准换行字符与std::endl
- 在字符数组中插入新的换行符
- 正在搜索换行符'n'字符串对象中的字符
- cin.get()缓冲区中的左换行字符
- 如何在c++中从字符串中获得子字符串到第一个换行字符
- 剥离换行字符的方法
- 在无符号字符数组中读取充满字符串(用换行符分隔)的文件(反之亦然)的最快方法是什么?
- 使用CFile检查换行符(换行字符)
- 用换行移位字符?c++
- 将文件的前1000个字符读入缓冲区,将换行符转换为 ,并将字符串的地址位置存储为char*[]