这个有点难,最大的努力给高分
01.01136514996540.12
01.01114160.33
01.09111937.48
01.09212224.2
01.11118591.27
01.1311837.35
01.14114957.11
01.241131151.52
01.3143194994.89
01.314330716.3
这个是我读取文件中的一小部分,要求的是一定要用string来写,我现在的要求是分行读取操作,先将第一行的三个数据依据空格判断方式分开成三部分存储在数组里面。然后再取出第一部分,也就是01.011对他进行判断是否含有小数点,有小数点,只保留小数点后一位,麻烦了各位,本人会尽力给最高分,先说声谢谢了
[解决办法]
as promised in 1L, 上代码:
- 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<string> column2; // 用于存放第二列数据 vector<string> column3; // 用于存放第三列数据 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(period_processing(str2)); column3.push_back(period_processing(str3)); } fis.close(); // 检查column1、2、3中的数据是否符合要求 for(int i = 0; i < column1.size(); ++i) { cout << column1[i] << "\t" << column2[i] << "\t" << column3[i] << endl; } // 如果要将所有的数据转型成float/int,这个应该很容易,不用再说了吧:) return 0;}