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

 

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