繁体   English   中英

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

[英]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 */
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM