C++IO库--fstream和stringstream

注意:IO对象无拷贝或赋值,需要以引用的方式传递参数和返回流。

 istringstream和ifstream的使用  

 (1)使用ifstream从文件中读取文本,一行为一个元素存入vector<string>中;  
 (2)使用istringstream从vector<string>读取元素,每次读一个单词  
 (3)使用ifstream从文件中读取文本,每次读一个单词

 

程序实例来自于C++Primer(第5版)第八章的练习题,将多道练习题整合到一个程序中;

在程序中,通过注释的方式说明了文件流和字符串流的使用。

// istringstream和ifstream的使用
// (1)使用ifstream从文件中读取文本,一行为一个元素存入vector<string>中;
// (2)使用istringstream从vector<string>读取元素,每次读一个单词
// (3)使用ifstream从文件中读取文本,每次读一个单词
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
#include<sstream>
using namespace std;

int main(int argc, char**argv)
{
	string infile = "1.txt";
	vector<string> vecline;
	ifstream in(infile);
	//检查文件读取是否成功
	if (in)
	{
		string buf;
		//(1)
		while (getline(in, buf))
		{
			vecline.push_back(buf);
		}
	}
	else
	{
		cerr << "cannot open this file: " << infile << endl;
	}

	for (int i = 0; i < vecline.size(); ++i)
	{
		//(2)
		istringstream iss(vecline[i]);
		string word;
		while (iss >> word)
			cout << word;
		cout << endl;
	}
	in.close();

	//(3)
	vector<string> vecword;
	in.open(infile);
	if (in)
	{
		string buf;
		while (in >> buf)
		{
			vecword.push_back(buf);
		}
	}
	else
	{
		cerr << "cannot open this file: " << infile << endl;
	}
	for (int i = 0; i < vecword.size(); ++i)
	{
		cout << vecword[i] << endl;
	}
	in.close();
	return 0;
}

ofstream 向txt写东西:https://blog.csdn.net/yang332233/article/details/79412817

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章