2016-02-14 24 views
2

我正在編寫處理大部分文本的程序,並且需要刪除標點符號。我遇到了Debug Assertion Failed錯誤,並將其隔離爲:在非英文字母上測試ispunct()時發生此錯誤。調試聲明使用ispunct時失敗('ø')

我的測試程序,現在是這樣的:

的main.c

int main() { 
    ispunct('ø'); 
    cin.get(); 
    return 0; 
} 

的調試斷言失敗窗口如下所示: Screenshot of the error

所有非英文字母我已嘗試引起此問題,包括'æ','ø','å','é'等。標點符號和英文字母不會導致問題。這可能很簡單,我可以忽略,所以我很感激任何幫助!

+1

閱讀[文檔](http://en.cppreference.com/w/cpp/string/byte/ispunct)會告訴你'ispunct'要求該值可以表示爲'unsigned char',或者是EOF。它完全取決於系統,這個代表的是什麼。 – chris

+0

非常感謝!你有沒有關於如何實現刪除守時功能的建議呢?目前我正在使用 'string word =「søme。?。thing」;''word.erase(remove_if(word.begin(),word.end(),ispunct),word.end());' 理想情況下,它應該修剪線「sømething」,但「ø」使它失敗 – oyvind

+1

如果你正在處理實際的Unicode字符串,那麼適當的Unicode庫可能是一個好主意。否則,'wchar_t'至少是一個快速解決方案。 – chris

回答

2

'ø'必須可以表示爲一個unsigned char,否則你應該使用類型wchar_tstd::ispunct,例如:

#include <iostream> 
#include <locale> 

int main() 
{ 
    const wchar_t c = L'ø'; 

    std::locale loc("en_US.UTF-8"); 

    std::ispunct(c, loc); 
} 

對於你的問題,你也可以這樣做:

#include <locale> 
#include <string> 
#include <algorithm> 
#include <functional> 

int main() 
{ 
    std::wstring word = L"søme.?.thing"; 

    std::locale loc("en_US.UTF-8"); 

    using namespace std::placeholders; 

    word.erase(std::remove_if(word.begin(), word.end(), 
      std::bind(std::ispunct<wchar_t>, _1, loc)), word.end()); 

    std::wcout << word << std::endl; 
} 
+0

謝謝!但是,嘗試此代碼給我一個錯誤。它似乎是'std :: locale loc(「en_US.UTF-8」);''導致問題。錯誤消息如下所示:NaiveBayesClassifier.exe中的0x75AC5B68未處理的異常:Microsoft C++異常:內存位置0x00C5F870處的std :: runtime_error。 – oyvind

+0

我在啓用C++ 11的情況下使用gcc。 – deepmax

+0

@oyvind捕獲異常以查看錯誤消息,但可能該語言環境在您的系統上不存在。您可以更改爲'std :: locale loc;'在Windows編譯器上使用默認語言環境 –