主题:怎么才能打开文件?请高手们指点指点我啊
//从输入设备读入文本,对不在排除集中的单词进行出现次数统计
#include<iostream>
#include<fstream>
#include<map>
#include<vector>
#include<string>
using namespace std;
void restricted_wc(ifstream &removeFile,map<string,int>&wordCount)
{
vector<string>excluded;//保存被排除单词
string removeWord;
while(removeFile>>removeWord)
excluded.push_back(removeWord);
//读入文本并对不在排除集中的单词进行出现次数统计
cout<<"Enter text(Ctr+Z to end):"<<endl;
string word;
while(cin>>word){
bool find=false;
//确定单词是否在排除集里
vector<string>::iterator iter=excluded.begin();
while(iter!=excluded.end()){
if(*iter==word){
find=true;
break;
}
++iter;
}
//如果单词不在排除集中,进行计数
if(!find)
++wordCount[word];
}
}
int main()
{
map<string,int>wordCount;
string fileName;
//读入包含单词排除集的文件的名字并打开相应文件
cout<<"Enter fileName"<<endl;
cin>>fileName;
ifstream exFile(fileName.c_str());
if(!exFile){//打开文件失败
cout<<"error:can not open file:" <<fileName<<endl;
return -1;
}
//进行单词统计
restricted_wc(exFile,wordCount);
//输出统计结果
cout<<"word\t\t"<<"times"<<endl;
map<string,int>::iterator iter=wordCount.begin();
while(iter!=wordCount.end()){
cout<<iter->first<<"\t\t"<<iter->second<<endl;
iter++;
}
return 0;
}
我不明白文件exFile中的单词从何而来?我直接将上面的代码复制运行,总是输出error:can not open file,所以我想问下,文件到底是怎么回事?它里面的单词从何而来?能否为我详细讲解下。小弟自学c++,遇到问题没人问,还望各位高手们不吝赐教!
#include<iostream>
#include<fstream>
#include<map>
#include<vector>
#include<string>
using namespace std;
void restricted_wc(ifstream &removeFile,map<string,int>&wordCount)
{
vector<string>excluded;//保存被排除单词
string removeWord;
while(removeFile>>removeWord)
excluded.push_back(removeWord);
//读入文本并对不在排除集中的单词进行出现次数统计
cout<<"Enter text(Ctr+Z to end):"<<endl;
string word;
while(cin>>word){
bool find=false;
//确定单词是否在排除集里
vector<string>::iterator iter=excluded.begin();
while(iter!=excluded.end()){
if(*iter==word){
find=true;
break;
}
++iter;
}
//如果单词不在排除集中,进行计数
if(!find)
++wordCount[word];
}
}
int main()
{
map<string,int>wordCount;
string fileName;
//读入包含单词排除集的文件的名字并打开相应文件
cout<<"Enter fileName"<<endl;
cin>>fileName;
ifstream exFile(fileName.c_str());
if(!exFile){//打开文件失败
cout<<"error:can not open file:" <<fileName<<endl;
return -1;
}
//进行单词统计
restricted_wc(exFile,wordCount);
//输出统计结果
cout<<"word\t\t"<<"times"<<endl;
map<string,int>::iterator iter=wordCount.begin();
while(iter!=wordCount.end()){
cout<<iter->first<<"\t\t"<<iter->second<<endl;
iter++;
}
return 0;
}
我不明白文件exFile中的单词从何而来?我直接将上面的代码复制运行,总是输出error:can not open file,所以我想问下,文件到底是怎么回事?它里面的单词从何而来?能否为我详细讲解下。小弟自学c++,遇到问题没人问,还望各位高手们不吝赐教!