C++学习笔记(6)

C++ Primer Chapter 8

  • log可以使用现成的library,不用造轮子
  • file可以调用现有项目的借口

实际开发中自己写file-system很少

fstream

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#include<fstream>

int main(){
//                    |filename      |mode
    std::ofstream os("file.txt", std::ios::app);
    os << "hello world!";//输入hello world!到os

    //buffer
    os.flush();
    os.close();

    std::ifstream is("file2.txt");

    string str;
    getline(is, str); //从is中读取一行到str
    cout << str << endl;

    is.close();
}

sstream

分词,用于leetcode

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#include<string>
#include<sstream>
using std::cout;
using std::endl;
using std::string;

int main(){
    string raw_string = "dsf dsf h trjhytjyt jkuyke dffh";
    std::stringstream ss(raw_string);
    int count = 0;
    string word;
    while(ss >> word){
        count ++;
        cout << word << endl;
    }
    cout << count << endl;

}