c++ 按行读txt文件与字符串写入txt文件

#include<iostream>
#include<fstream>
#include<string>

int main()
{
    // 向文件里写数据
    std::ofstream os;     //创建一个文件输出流对象
    // os.open("../books.txt", std::fstream::out|std::fstream::app);//将对象与文件关联, app就是每次在文件后面继续添加内容
    os.open("../test.txt", std::fstream::out);//将对象与文件关联
    for(int i=0; i < 10; i ++)
    {
        std::string str = "hello world\n";
        os<<str;   //将输入的内容放入txt文件中
    }
    os.close();

    // 按照行读取文件中的数据
    std::ifstream in;
    in.open("../test.txt");
    std::string line;
    while(getline(in, line))    // line中不包括每行的换行符
    {
        std::cout << line << std::endl;
    }
    return 0;
}



版权声明:本文为Guo_Python原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。