难题,求解决
这个其实具体的题目,他只是给我个例子,叫我照着他的要求去写,我现在就把具体要求给你详细说一遍把,是这样的01.011 365 14996540.12
01.011 1 4160.33
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这是一个文本文件,要求的是先将他读取,依据空格将他们分成三个,然后只对第一列进行判断是否有小数点有小数点的话就保留第一位小数,然后对比后面的各行,如果后面的第一列数字和第一行相等的话,就在其后另起一行对前面的数进行一次叠加对这个例子就是1,2行进行一次叠加,3,4行进行一次叠加右面的以此类推,就这样,麻烦了各位,如果还有什么不懂得就问,谢谢啦,各位
[解决办法]
哥啥也不说,直接上代码(刚做了一个一模一样的题目):
- C/C++ code
#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;}