今天去趋势科技笔试做了这样一题,到现在还没搞明白,这一题类似这个题目:http://blog.csdn.net/u012243115/article/details/44784223
程序如下:
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
using namespace std;
int main()
{
for(int i = 0 ; i < 2 ; i++)
{
cout<<"-\n";
fork();
cout<<"-\n";
}
cout<<endl;
}
问结果输出多少个”-“。
按照分析cout<<”\n”并不刷新缓冲区,结果应该是输出16个-,但是实际只输出了9个-,说明刷新了缓冲区。如果把cout后面的\n去掉,即程序变成下面这样:
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
using namespace std;
int main()
{
for(int i = 0 ; i < 2 ; i++)
{
cout<<"-";
fork();
cout<<"-";
}
cout<<endl;
}
结果输出了16个-:
说明去掉\n肯定没有刷新缓冲区,但是加上\n为什么刷新了缓冲区,对于这个很是不理解。