簡體   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