20200217
Plan
60min: CPP
Notes
std io 标准库
整体以练习为主,大概熟悉了常用用法:
#include <iostream>
#include <fstream>
std::istream& echo(std::istream &in) {
std::string buffer;
auto old_state = in.rdstate();
while(in >> buffer) {
std::cout << buffer << std::endl;
}
in.setstate(old_state);
return in;
}
void tie_test(std::istream &in, std::ostream &out) {
// uncomment this line will cause next line wont be output immediately
/* in.tie(nullptr); */
out << "in buffer";
std::string buffer;
while(in >> buffer){}
}
void read_lines_from_file(std::string file_name, std::string out_file_name) {
std::ifstream f(file_name);
std::ofstream out_f(out_file_name, std::ofstream::app);
std::string line;
while(getline(f, line)) {
out_f << "found new line:" << line << std::endl;
}
}
int main() {
read_lines_from_file("./io_test_file", "output");
return 0;
}
值得记录的点:
- 三个重要头文件:
<iostream> <fstream> <sstream> - tie 作为 istream 的方法,可以绑定到一个 ostream 上,其作用是在 istream 的任意读开始,flush ostream 的缓冲区
- getline 函数作为行处理十分方便
- macos 下,newline+ctrl+D == EOF
- while(std::cin >> buffer) 可以作为读完一个流的标准形式
More
- std::cin >> buffer 的返回值是什么?