如何输入以特殊字符开头的字符串
How to input strings that start with special characters
我试图用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 */
}
其余代码(假设它没有错误)应该没问题
相关文章:
- 如何用转义符替换字符串中的所有特殊字符
- 转换特殊字符(UTF-8)
- 反转字符串中单词的位置,而不更改 O(1) 空格限制中特殊字符的顺序
- 如何在C++中打印此"█"特殊字符?
- c++为什么ifstream get()函数返回无法识别的特殊字符
- 如何检查字符串是否包含所有这些:数字、字母和特殊字符
- 转义std::字符串中的特殊字符
- SDL2加载具有特殊字符的文件
- 将 std::string 转换为具有特殊字符的 FString (TCHAR / wstring)
- 如何打印以特定字符开头的单词数?
- 如何从文本文件C++读取整数和特殊字符
- USB序列号显示特殊字符
- 键入特殊字符并保存在文件中
- 回文,不包括特殊字符和空格
- 无法使用 Unicode 特殊字符设置窗口文本
- 使用 libmysql 插入特殊字符
- 使用具有特殊字符的正则表达式标记 C++ 字符串
- 如何输入以特殊字符开头的字符串
- 如何使用正则表达式匹配不包含特殊字符(&、\、<、>、|、)的字符串,除非它们以反斜杠开头
- C++降低特殊字符,例如 ü