65,187
社区成员




01.0 365 14996540.12
01.0 1 4160.33
01.0 1 1937.48
01.0 1 2224.20
01.0 368 15004862.13 // 新增的
01.1 1 8591.27
01.1 1 837.35
01.1 1 4957.11
01.1 3 14385.73 // 新增的
01.2 1 31151.52
01.3 3 194994.89
01.3 3 30716.30
01.3 6 225711.19 // 新增的
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
string period_processing(string str) // 如果有小数点,则仅保留小数点后面1位
{
size_t pos = str.find_first_of(".");
if(pos != string::npos)
{
str = str.substr(0, pos + 2);
}
return str;
}
int main(int argc, char** argv)
{
char row[100]; // 用于获取文件中的一行
int pos1; // 每行中第一个空格的位置
int pos2; // 每行中第二个空格的位置
vector<string> column1; // 用于存放第一列数据
vector<int> column2; // 用于存放第二列数据
vector<double> column3; // 用于存放第三列数据
vector<string> column21;
vector<int> column22;
vector<double> column23;
ifstream fis("E:/testfile.txt"); // 假定文件在E盘的根目录下,文件名为testfile.txt
if(!fis)
{
cout << "Can not open file..." << endl;
exit(1);
}
while(fis)
{
memset(row, 0, 100);
fis.getline(row, 100); // 从文件中读取一行
string aline(row);
pos1 = aline.find_first_of(" ");
pos2 = aline.find_last_of(" ");
string str1 = aline.substr(0, pos1); // 获取每行的第一列内容
string str2 = aline.substr(pos1 + 1, pos2 - pos1 - 1); // 获取每行的第二列内容
string str3 = aline.substr(pos2 + 1); // 获取每行的第三列内容
column1.push_back(period_processing(str1));
column2.push_back(atoi(str2.c_str()));
column3.push_back(atof(str3.c_str()));
}
fis.close();
int sum1 = 0;
double sum2 = 0.0;
for(int i = 0; i < column1.size(); ++i)
{
if(i > 0 && column1[i] == column1[i - 1])
{
sum1 += column2[i - 1];
sum2 += column3[i - 1];
}
if(i > 0 && column1[i] != column1[i - 1])
{
sum1 += column2[i - 1];
sum2 += column3[i - 1];
if(sum1 != column2[i - 1])
{
column21.push_back(column1[i - 1]);
column22.push_back(sum1);
column23.push_back(sum2);
}
sum1 = 0;
sum2 = 0.0;
}
column21.push_back(column1[i]);
column22.push_back(column2[i]);
column23.push_back(column3[i]);
}
// 将得到的结果写到另外一个文件中
ofstream fos("E:/result.txt");
for(int i = 0; i < column21.size() - 1; ++i)
{
if(i != 0)
{
fos << endl;
}
char c3[20] = {0};
sprintf(c3, "%.2f", column23[i]);
fos << column21[i] << " " << column22[i] << " " << c3;//column23[i];
}
fos.close();
return 0;
}
01.011 365 14996540.12
01.011 1 4160.33
01.091 1 1937.48
01.092 1 2224.2
01.011 365 14996540.12
01.011 1 4160.33
//02.02 366 15000700.4 1. 确定是增加一行吗?2. 第一个字段也需要相加吗?
//01.01 366 15000700.4 3. 如果后面第一个字段还出现01.01,应该如何处理?还是肯定不会出现?
01.091 1 1937.48
01.092 1 2224.2
01.111 1 8591.27
01.131 1 837.35
01.141 1 4957.11
01.241 1 31151.52
01.314 3 194994.89
01.314 3 30716.3