C++读写文本

C++读写文本

软件开发中经常会有遇到用于交换数据的文本的读写,常常我们会引用json库进行json文件格式的读写,本文记录一下常用的普通文本的读写.

1.读取空格分隔的文本

test.txt 本文内数据用空格分隔:

/*
 * test.txt:
 * 11  22 33
 * 44  55 66
*/
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
	string fileName = "D:\\test.txt";
	std::ifstream  fin(fileName.c_str(), std::ios::in);
	char line[512] = { 0 };
	while (fin.getline(line, sizeof(line))) { // 每行内容读取到字符数组line中
		std::stringstream ss(line);
		if (ss.rdbuf()->in_avail() != 0) { //避免读入空行
			int n1, n2, n3;
			ss >> n1;
			ss >> n2;
			ss >> n3;
			cout << n1 << " " << n2 << " " << n3 << endl;
		}
	}
	fin.close();
}
/*
 * 控制台打印:
 * 11 22 33
 * 44 55 66
*/

2.读取符号分隔的(逗号为例)文本

test.txt 本文内数据用’,'分隔:

/*
 * test.txt:
 * 11, 22,   33
 * 44, 55,66
*/
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
	string fileName = "D:\\test.txt";
	std::ifstream  fin(fileName.c_str(), std::ios::in);
	char line[512] = { 0 };
	while (fin.getline(line, sizeof(line))) { // 每行内容读取到字符数组line中
		string strline = line;
		for (size_t i = 0; i < strline.length(); ++i) {
			if (',' == line[i]) {
				line[i] = ' ';
			}
		}
		std::stringstream ss(line);
		if (ss.rdbuf()->in_avail() != 0) { //避免读入空行
			int n1, n2, n3;
			ss >> n1;
			ss >> n2;
			ss >> n3;
			cout << n1 << " " << n2 << " " << n3 << endl;
		}
	}
	fin.close();
}
/*
 * 控制台打印:
 * 11 22 33
 * 44 55 66
*/

3.写入文本

	ofstream fout;
	string fileName = "E:\\test.txt";
	fout.open(fileName.c_str(), ios_base::out);
	//fout.open(fileName.c_str(), ios::app); //追加方式
	if (fout.is_open()) {
		fout << "It's me Mario!\n";
	}
	fout.close();
/*
 * test.txt:
 * It's me Mario!
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值