C++IO库--fstream和stringstream

本文介绍如何使用C++中的ifstream和istringstream进行文件和字符串流处理。具体包括从文件中逐行读取并存储为vector<string>,再从该vector中逐词读取,以及直接从文件中逐词读取的方法。通过实际代码演示了这些操作的具体实现。

注意: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

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值