我试图将所有单词输入到 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)
我输入的是长歌歌词文件。以下是程序卡住的词:
数星星:已完成。
我可以让你拍手:卡在原因
再过一晚:困在(是的
运行测试(测试组合词的文件):已完成
安全舞:困在'em
摆脱它:卡在“哦
还有很多其他人遵循相同的模式。前面始终有 1 个或多个特殊字符。你可以自己试试,输入前面有特殊字符的字符串,cin >> string会卡住。
最终编辑:错误出现在 stripWord 函数中,所以这个问题只是一个糟糕的问题。
最佳答案
这段代码:
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 */
}
其余代码(假设它没有错误)应该没问题
关于c++ - 如何输入以特殊字符开头的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55896918/