2012-03-21 234 views
0

我看了各種方法,從string.erase/ispunct等等,我不能簡單地得到它爲我的代碼工作。從字符串c中刪除單引號字符C++

我的代碼如下:

ifstream infilei("test.txt") 

**Second part of code......** 

while (!infilei.eof()) 
{ 
    string wordlist; 
    infilei >> wordlist; 
    inputlist.push_back(wordlist); 
} 

的的text.txt包含逗號,單引號,雙引號等等,我需要將它們刪除。

其中infilei >> wordlist;顯示,我試圖使用if語句刪除字符串與'「'等,但它仍然不會刪除單引號或雙引號。是否有另一種方法或我可以設置一個string.erase爲?超過一定ASCII範圍,是一種方法,也送字符串的push_back期間小寫

謝謝

+0

向我們展示您嘗試的「if語句」。 – 2012-03-21 21:21:03

+0

我試過這個,但仍然沒有刪除信號或雙引號: while(!infilei.eof()){string wordlist; while(infilei >> wordlist){for(int i = 0; i MacKey 2012-03-21 21:54:39

回答

1

你應該寫if語句,像這樣if(str[i]=='\"' or str[i]=='\'')並以此爲小寫這應該這樣做?

std::transform(str.begin(), str.end(), str.begin(), ::tolower); 
+0

我已經試過了,並且會重新試一試,謝謝 – MacKey 2012-03-21 20:09:50

+0

我試過了,但仍然沒有刪除信號或雙引號: \t while(!infilei.eof )) \t { \t \t串單詞表; \t \t而(infilei >>單詞表) \t \t { \t \t \t for(int i = 0;我 MacKey 2012-03-21 20:13:28

+0

std :: transform(str.begin(),str.end(),str.begin(),:: tolower);完美的作品。 – MacKey 2012-03-21 22:36:01

1

這段代碼將清理每個「,」。 'from mesy_string:

#include <iostream> 
#include <algorithm> 
#include <string> 

using namespace std; 

//Chars to be removed 
bool has_chars(char c){ 
    if(c=='\"' || c=='.' || c==',' || c=='\'') 
    return true; 
    else 
    return false; 
} 

int main() { 
    string messy_string="dfffsg.nfgfg,nsfvfvbnf\"nsdfnsdf\'ssvbssvns\"hhhfh\""; 

    cout<< messy_string<<endl; 

    remove_if (messy_string.begin(), messy_string.end(), has_chars); 

    cout<< messy_string<<endl; 
    return 0; 
} 

您應該可以根據需要進行修改。

+0

嘗試,但無濟於事。感謝您的幫助。 – MacKey 2012-03-21 21:56:34