Skip to content

Commit 1496935

Browse files
authored
Update cpp_tricks.md
1 parent 89e6408 commit 1496935

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

docs/cpp_tricks.md

+20-2
Original file line numberDiff line numberDiff line change
@@ -978,8 +978,26 @@ cout << "Hello, World!" << '\n';
978978

979979
endl 是一个典型的以讹传讹错误写法,只有当你的输出是指向另一个进程的管道时,其附带的刷新功能才有作用。
980980

981-
- 当输出是管道时,`cout` 需要 `endl` 才能刷新。
982-
- 当输出是普通控制台时,`cout` 需要 `endl` 才能刷新。
981+
- 当输出是管道或文件时,`cout` 需要 `endl` 才能刷新。
982+
- 当输出是普通控制台时,`cout` 只需 `'\n'` 就能刷新了,根本用不着 `endl`
983+
984+
而且,管道或文件实际上也不存在频繁刷新的需求,反正 `ifstream` 析构时总是会自动刷新写入磁盘。
985+
986+
因此,`endl` 操纵符大多时候都是冗余的:控制台输出的 `cout` 只需要字符或字符串中含有 `'\n'` 就刷新了,即使是文件读写也很少会使用 `endl`
987+
988+
如果确实需要强制刷新,也可以用 `flush` 这种更加可读的写法:
989+
990+
```cpp
991+
int num;
992+
cout << "please input the number: " << flush;
993+
cin >> num;
994+
995+
ofstream fout("log.txt");
996+
fout << "immediate write 1\n" << flush;
997+
sleep(1);
998+
fout << "immediate write 2\n" << flush;
999+
fout.close(); // 关闭文件时总是自动 flush,不会有残留未写入的字符
1000+
```
9831001
9841002
## 多线程中 cout 出现乱序?
9851003

0 commit comments

Comments
 (0)