使用c++标准IO库实现txt文本文件的读与写操作

练习c++primer中关于输入输出流的操作。

任务是从固定格式的forreading.txt文档中读取相应的数据,转存到forwriting.txt中去。

forreading.txt 格式如下:

(12)(13)(34)(1099)
(23)(28)(29)(25)
(32)(45)
(123)
(120)(333)(1)(8)
(34)(45)
(90)(110)

 希望读取其中数字,并以空格为间隔符号存在forreading当中,代码如下:

/*针对的数据格式如下*/
/*(23)(26)          */
/*(34)(45)(67)(89)  */
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

int main()
{
	ifstream infile;
	infile.open( "forreading.txt" );
	ofstream outfile;
	string line, word,temp_str;
	vector<vector<string> > a;
	bool flag_begin{ false }, flag_end{ false };

	while (getline(infile, line))
	{
		vector<string> a_i;
		istringstream stream(line);
		while (stream >> word)
		{
			for (string::iterator iter = word.begin(); iter != word.end(); iter++)
			{
				char llabel = 40,rlabel=41;//这两个数值对应着“()”的asc码
				if (*iter == llabel)
				{
					flag_begin = true; flag_end = false; continue;
				}
				if (*iter == rlabel)
				{
					flag_end = true; flag_begin = false;
				}

				if ((flag_begin == true) && flag_end == false)
				{
					temp_str.push_back(*iter);
				}
				if ((flag_begin == false) && flag_end == true)
				{
					a_i.push_back(temp_str);//这里仍然无法实现将string转换成数字,而是以string的形式保存下来
					temp_str.clear();
					/*a = atoi(temp_str);*/
				}
			}
		}
		a.push_back(a_i);
		a_i.clear();
	}
	outfile.open("forwriting.txt");
	for (vector<vector<string> >::iterator iter_out = a.begin(); iter_out != a.end(); iter_out++)
	{
		for (vector<string>::iterator iter_iner = (*iter_out).begin(); iter_iner != (*iter_out).end(); iter_iner++)
		{
			cout << *iter_iner << " ";
			outfile << *iter_iner << " ";
		}
		cout << endl;
		outfile << "
";
	}
	return 0;
}

 在Ubuntu中makefile内容为:

edit:readtxtfile.o
	g++ -o edit readtxtfile.o
readtxtfile.o:readtxtfile.cpp
	g++ -c readtxtfile.cpp
clean :
	rm readtxtfile.o

 输出的forwriting.txt为:

12 13 34 
23 28 29 25 
32 

 总结:这里仍然要根据txt的具体组织格式去读取,并不能通用。另外,从string变量直接转换成int变量的方法还有待探究。个人感觉用c的处理方法可能会更方便一些,有时间可以做一下尝试。

原文地址:https://www.cnblogs.com/simayuhe/p/5846297.html