C++中IO流的基本操作

#include<iostream> #include<fstream> #include<string> #include<sstream> using namespace std; int main() { cout<<"hello flush"<<flush; cout<<"hello ends"<<ends; cout<<"hello endl"<<endl; /* //test cin.clear() && cin.sync() int ival; cout<<"input ival:"<<endl; cin>>ival; while(!cin.eof()) { if(cin.bad()) throw runtime_error("IO stream corrupted"); if(cin.fail()) cerr<<"bad data,try again"<<endl; cin.clear(); cin.sync(); cin>>ival; } */ //在一个给定文件中搜索单词,结果保存到另一个文件中 ifstream infile; ofstream outfile; string filename; string line,word,searchword; int countline=0,countword=0; cout<<"input the word to search:"; cin>>searchword; cout<<"input filename:"; cin>>filename; infile.close(); infile.clear(); infile.sync(); infile.open(filename.c_str(),ifstream::in); if(!infile) { cout<<filename<<" open error!"<<endl; return 0; } else { cout<<filename<<" open success!"<<endl; //to use file while(getline(infile,line))//逐行读入处理 { countline++; istringstream stream(line);//绑定 while(stream>>word)//逐个单词处理 { if(word==searchword) countword++; } } //cout<<countline<<endl; //cout<<countword<<endl; outfile.open("out.txt",ofstream::out|ofstream::app);//追加写入文件out.txt outfile<<"row number of "<<filename<<":/t"<<countline<<endl; outfile<<"word /""<<searchword<<"/" appears "<<countword<<" times"<<endl; cout<<"row number of "<<filename<<":/t"<<countline<<endl; cout<<"word /""<<searchword<<"/" appears "<<countword<<" times"<<endl; } return 0; }

你可能感兴趣的:(C++,Stream,IO,search,input)