2016-10-17 66 views
0

我寫了一個功能空間&之前刪除從一個句子的空間,但其只考慮字符不考慮整個句子。 如果我跑了這一點賣出期權我已經寫了一個函數從一個句子中的空格,但其只考慮字符的空間之前和不考慮整個森泰斯

Enter the string with space/ tab to trim 
IamDoing very fine 
Length of the String is : 8 
IamDoing 

我什麼樣的變化,我需要做得到「IamDoingveryfine」 請幫幫忙,代碼如下......」

void removeSpace(const string &str) 
{ 
    string tempStr; 
    string p_str = str; 
    int l_length = p_str.length(); 
    cout<<"Length of the String is : "<<l_length<<endl; 
    for (int i=0; i<l_length; i++) 
    { 
     if(p_str[i] != ' ' || p_str[i] != '\t') 
     { 
      tempStr +=p_str[i]; //to add chars into tempstr 
     } 
    } 
    cout<<tempStr<<'\n'; 
    return ; 
} 
+0

請你能張貼在那裏你字符串中讀取的代碼,你應該做'的std ::函數getline()'取代'的std :: CIN >>讀入。而你的'||'應該是'&&'。 –

+0

所有字符與空格和製表符中的至少一個不同。 「如果字符不是空格或製表符」,則將其翻譯爲「如果字符不是空格且字符不是製表符」。 – molbdnilo

+0

德摩根定理:「如果它是一個空格或製表符,則將其刪除」與「如果它不是空格**和**而不是製表符」保持一致。這就是說,這是一個容易犯的錯誤。 –

回答

1

的問題是不該removespace()問題,當你正在服用的輸入

它應該是這樣的:

std::string line; 
std::cout << "Enter the string with space/ tab to trim" << std::endl; 
std::cin.getline (line); 
0

我用 std :: getline(std :: cin,name); 輸入問題與此解決。但在修剪功能,即使即時檢查'''&''噸'我不能夠阻止白色空間。

removeSpace應該丟失一些東西。

+0

編輯您的問題,請勿將更新發布爲答案。 –

0

我修改函數來獲得預期的答案如下

void removeSpace(const string &str) 
{ 
    string tempStr; 
    string p_str = str; 
    int l_length = p_str.length(); 
    cout<<"Length of the String is : "<<l_length<<endl; 
    for (int i=0; i<l_length; i++) 
    { 
     if((p_str[i] == ' ') || (p_str[i] == '\t')) 
     { 
      continue; 
     } 
     else 
     { 
      cout<<p_str[i]<<endl; 
      tempStr +=p_str[i]; //to add chars into tempstr 
     } 
    } 
    cout<<tempStr<<'\n'; 
    return ; 
} 

但是當我用IF(p_str [I]!= '' || p_str [I]!= '\ t')函數無法丟棄的空間,任何人可以告訴我爲什麼這種差異

相關問題