我正在尝试将所有单词输入C ++中的映射中,但是该程序仅在单词以特殊字符开头时冻结。当末尾有特殊字符时,该代码才有效。
我无法找到C ++中>>运算符的正确文档,也无法正确搜索我的问题。
//Map values and find max value
//The code works for all words except the ones that start with special characters
while(myFile >> cWord){
//put the characters into a string
//DEBUG: cout << "real word: " << cWord << " | ";
cWord = stripWord(cWord);
//delete common words before they're in the system
if(cWord == "a" ||
cWord == "an" ||
cWord == "and" ||
cWord == "in" ||
cWord == "is" ||
cWord == "it" ||
cWord == "the"){
continue;
}
if (wordMap.count(cWord) == 0){
wordMap.insert({cWord, 1});
}
else{
wordMap[cWord]++;
if(wordMap[cWord] > maxWordRep){
maxWordRep = wordMap[cWord];
}
}
//DEBUG: cout << cWord << " | " << wordMap[cWord] << endl;
}
我希望调试先打印所有单词,然后再执行其余代码,但是代码停止运行并冻结在确切的行上
while(myFile >> cWord)
我输入的是长歌歌词文件。这些是程序冻结的词:
数星星:已完成。
我可以拍拍手:卡在原因
再住一个晚上:卡在(是
运行测试(用于测试组合词的文件):已完成
安全舞蹈:卡在他们
摆脱掉:卡在“哦
还有很多其他人遵循相同的模式。总是前面有1个或更多特殊字符。您可以自己尝试,当您输入的字符串前面带有特殊字符时,cin >>字符串将被卡住。
答案 0 :(得分:0)
此代码:
while(myFile >> cWord)
>>运算符返回std :: istream&,因此此处调用的运算符为:http://www.cplusplus.com/reference/ios/ios/operator_bool/
是否注意到它正在寻找要在istream上设置的故障位?读取到文件末尾不是错误,因此,实际上,您应该检查是否已到达文件末尾,例如
while(!myFile.eof())
{
myFile >> cWord;
/* snip */
}
如果文件末尾有一堆无意义的空格,您可能最终会在文件末尾读取一个空字符串,这也应加以注意,例如
while(!myFile.eof())
{
myFile >> cWord;
if(cWord.empty()) break;
/* snip */
}
其余代码(假设它没有错误)应该没问题