我们在日常处理问题时经常要进行数据的读写操作,而这些数据最常用的存储格式就是txt文本了。下面我们就来简单介绍一下如何通过C++对文本中的数据进行处理。
首先我们来引入头文件,C++为我们提供了iostream库(输入输出流,可以理解为in(输入) out(输出) stream(流),取in、out的首字母与stream合成); fstream是stream的子类,为我们提供了操作文件的众多方式(大家可以通过另外一篇文章对此进行更细致的了解)。
/*author: wxc_1998
date: 2019/7/3*/
#include
#include
同时为了程序后续功能的需要,我们还加入了:
#include //后续使用容器vector需要
#include //进行数学运算需要
接着我们主要使用fstream中的两个文件流子类:ifstream和ofstream。
ifstream可以用来打开数据文件,并进行读取操作,ofstream主要用于数据的写出操作。
其基本用法为:
ifstream open_file("文件路径");
open_file是ifstream类定义的一个对象,后面可以输入我们想要打开文件的绝对路径或者相对路径(注意:在输入文件路径时应使用“\\”,如"E:\\1\\scores.txt")。
在打开了我们想要读取的数据文件之后,我们可以直接通过运算符“>>”来进行读取操作,这种方式可以跳过空格,逐个读取文件中的所有字符,直到文件尾。
int temp;
while(!open_file.eof())
{
open_file >> temp;
my_score.push_back(temp);
}
除此之外,我们还有一种读取方法是:通过getline函数逐行读取数据。这种方法在对字符串数据文件中比较常用,当然,我们读取了每一行中的数据之后通常还需要对行字符串进行一些其他的操作。
string line;
while(!open_file.eof())
{
getline(open_file,line);
all_data.push_back(line);
}
其基本用法与ifstream类似:
ofstream out_file("写出文件路径");
out_file为ofstream类定义的对象名,括号内可以为想写出文件的任意路径。
创建写出文件之后,我们可以通过运算符"<<"来进行数据写出操作。
例如:
out_file << "min: " << my_min << endl;
out_file << "max: " << my_max << endl;
out_file << "ave: " << my_ave << endl;
out_file << "xigma: " << my_xig << endl;
这种使用方式类似于我们常用的cout显示,同时也可以对输出的格式进行调节以达到满意的效果。
最后我们以一个应用实例来结束本篇博客。
问题: 统计数据文件data.txt中的最大值、最小值并写出到result.txt中。
data.txt文件,第一个数代表数据的个数。
6
12 20 7 18 29 10
程序源代码:
/*author: wxc_1998
date: 2019/7/3*/
#include
#include
#include
using namespace std;
void main()
{
vector my_data;
int my_size = 0;
ifstream open_file("文件路径\\data.txt");
/*-------------------------读取数据文件------------------------------*/
if(open_file)
{
// cout << "成功打开文件!" << endl;
open_file >> my_size;
int temp;
while(!open_file.eof())
{
open_file >> temp;
my_data.push_back(temp);
}
}
else
cout << "打开文件时出现错误!" << endl;
/*-------------------------求取最大最小值------------------------------*/
int my_min = 1000, my_max = -1, my_sum = 0;
double my_ave = 0.0;
for (int i = 0; i != my_data.size(); ++i)
{
if(my_min > my_data[i])
my_min = my_data[i];
if(my_max < my_data[i])
my_max = my_data[i];
my_sum += my_data[i];
}
my_ave = (double)my_sum/(double)my_data.size();
cout << "min: " << my_min << endl;
cout << "max: " << my_max << endl;
cout << "ave: " << my_ave << endl;
ofstream out_file("文件路径\\result.txt");
out_file << "min: " << my_min << endl;
out_file << "max: " << my_max << endl;
out_file << "ave: " << my_ave << endl;
open_file.close();
out_file.close();
cout << endl << "press any key to continue!";
cin.clear();
cin.sync();
cin.get();
}