在做软件度量作业的过程中,遇到了文件中上千条记录的处理。程序如下:
C++的读文件
字符串取子串等
#include <iostream> #include <map> #include <fstream> #include <string> using namespace std; int main() { fstream fin; string filename = "E:\\002Validate Binary Search Tree\\Debug\\bugs-2013-11-30.csv"; fin.open(filename); if(fin.bad()) { cout<<"文件打开失败"<<endl; return 0; } string line; int first,last; string changeddata; map<string,int> count; while(!fin.eof()) { std::getline(fin,line); int comma = line.find_last_of(','); first = line.find_first_of('//',comma+1); last = line.find_first_of('//',first+1); if(first!=-1 && last!= -1) { if(first<5||last-first<1) continue; changeddata = line.substr(first-4,last-first+4); if(count.find(changeddata)==count.end()) count.insert(pair<string,int>(changeddata,1)); else count[changeddata] +=1; } } for(map<string,int>::iterator iter = count.begin();iter!=count.end();iter++) { //cout<< iter->first <<" "<< iter->second<<endl; //cout<< iter->first<<endl; cout<<iter->second<<endl; } return 0; }