首页 > 代码库 > 对c++ primer中 io文件输入输出流的理解

对c++ primer中 io文件输入输出流的理解

ifstream input_file("abcd.txt"); 创建一个输出流input_file流绑定到后缀txt的文件上,那么input_file就是一个输出流   相当与cin(cin >> s) 那么我们就可以用input_file >> s来代替cin,只不过cin是从键盘上输入,而input_file是从文件中读取的数据。


ofstream out_file("out_file.txt"); 同理这里out_file等同于cout,cout << n只不过是把数据输出显示在显示器上(媒介),而out_file << n是把数据输出到文件中txt中去保存起来.

让我们来看一个例子就好了:

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

using namespace std;

int main()
{
	vector<string> word;

	string s;

	string line;

	ifstream input_file("chenxun.txt");//which is the inputfile

	ofstream out_file("out_file.txt");//which is the outputfile

	//while (getline(input_file, line))
	//	cout << line << endl;


	while (!(input_file.eof()))
	{
		input_file >> s;

		out_file << s << endl;

		word.push_back(s);
	}

    cout << "this is a sb test ways" << endl;

	for (const auto &i : word)
		cout << i << " ";

	cout << endl;

}
看输入文件

看输出文件




对c++ primer中 io文件输入输出流的理解