如何输入以特殊字符开头的字符串

How to input strings that start with special characters

本文关键字:特殊字符 开头 字符串 何输入 输入      更新时间:2023-10-16

我试图用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>>字符串会卡住。

最终编辑:错误在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 */
}

其余代码(假设它没有错误)应该没问题