所以,我正在编写从用户接收文件的代码,删除所有标点符号。使文件小写并找到所有唯一的单词。问题不能正常工作,我不知道为什么。我没有打印出正确数量的唯一值
// convert charater to lowercase
void convert(char& ch){
ch = tolower(ch);
}
int main(){
typedef map<string,int> siMap;
typedef pair<siMap::iterator, bool>ibPair;
typedef siMap::value_type kvpair;
siMap myMap;
string fileName1;
string fileName2;
string value;
char ch;
// get user input
cout << "Please enter the first file Name: "; //asking for a file name
cin >> fileName1;
ifstream infile1;
infile1.open(fileName1.c_str());
//remove all punctuations
while (infile1.get(ch))
{
if (isalpha(ch) || isspace(ch)){
convert(ch);
}
else{
infile1.ignore(ch);
}
infile1 >> value;
myMap[value]++;
}
/*
for (int i = 0; i < 10; i++) {
cout << infile1[i];
} */
cout << " Map size is :" << myMap.size() << endl;
cout << "Please enter the second file Name: "; //asking for a file name
cin >> fileName2;
ifstream infile;
infile.open(fileName2.c_str());
}
答案 0 :(得分:-1)
你能提供你的第一个输入文件吗?你还记得在完成它之后关闭文件。对于调试部分,您可能希望使用map迭代器来找出缺少的单词。
// convert charater to lowercase
void convert(char& ch)
{
ch = tolower(ch);
}
int main()
{
typedef map<string,int> siMap;
typedef pair<siMap::iterator, bool>ibPair;
typedef siMap::value_type kvpair;
siMap myMap;
string fileName1;
string fileName2;
string value;
char ch;
// get user input
cout << "Please enter the first file Name: "; //asking for a file name
cin >> fileName1;
std::ifstream ifs(fileName1.c_str());
std::string content( (std::istreambuf_iterator<char>(ifs) ),
(std::istreambuf_iterator<char>() ) );
//remove all punctuations
for(std::string::iterator it = content.begin(); it != content.end(); ++it)
{
if (isalpha(*it))
{
convert(*it);
}
else
{
*it = ' ';
}
}
//now working on your map
std::stringstream ss;
ss.str (content);
string singleWord;
while (ss >> singleWord)
{
myMap[singleWord]++;
}
cout << " Map size is :" << myMap.size() << endl;
cout << "blahblah" << endl;
for (std::map<string,int>::iterator it=myMap.begin(); it!=myMap.end(); ++it)
std::cout << it->first << " => " << it->second << '\n';
cout << "Please enter the second file Name: "; //asking for a file name
cin >> fileName2;
ifstream infile;
infile.open(fileName2.c_str());
}