2014-10-11 86 views
-12

的字符串刪除標點符號有書中C++ Primer(數3.2.3)它要求一個練習:從人物

Write a program that reads a string of characters including punctuation and writes what was read but with the punctuation removed.

我試圖解決這個問題,但得到了一個錯誤:

#include <iostream> 
#include <string> 
using namespace std; 

int main() 
{ 
    string s; 
    cin >> "Enter a sentence :" >> s >> endl; 
    for (auto c : s) 
     if (ispunct(c)) 
      remove punct; 
     cout << s << endl; 


    } 
+2

...錯誤究竟是什麼? – Columbo 2014-10-11 16:01:50

+0

你應該在你的'if'和'for'語句中使用大括號來避免含糊不清。另外,'remove punct'沒有任何意義。 – 0x499602D2 2014-10-11 16:04:19

+0

正如你所看到的,這個問題並不需要你存儲結果。如果不是標點符號,爲什麼不逐一寫出每個字符? – 2014-10-11 16:04:31

回答

5

看看remove_if()

#include <iostream> 
#include <algorithm> 
#include <string> 
using namespace std; 

int main() 
{ 
    string s; 

    getline(std::cin,s); 

    cout << s << endl; 
    s.erase (std::remove_if(s.begin(), s.end(), ispunct), s.end()); 
    cout << s << endl; 
} 
+0

我喜歡這個想法,但是當我嘗試使用這個時遇到編譯器錯誤。 「錯誤:沒有匹配函數調用'remove_if'...」 – Trenin 2017-05-08 12:39:39

+0

@Trenin,你使用的是什麼編譯器? – CroCo 2017-05-08 20:08:22

+1

g ++ gcc版本6.3.0 20170406(Ubuntu 6.3.0-12ubuntu2) – Trenin 2017-05-09 11:31:34

2
int main() 
{ 
    string s; 
    cin >> "Enter a sentence : " >> s >> endl; 
    for (auto c : s) 
     if (ispunct(c)) 
      remove punct; 
    cout << s << endl; 
}

您的第一個問題是您使用的方式錯誤cincin用於標準輸入因此嘗試打印字符串和換行符是沒有意義的。這是cout工作:

cout << "Enter a sentence : "; 
cin >> s; 
cout << endl; 

的另一個問題是,作爲remove punct聲明並不意味着什麼編譯器。這是一個語法錯誤。既然你要打印不加標點的字符串,只打印僅ispunct()返回false:

for (auto c : s) 
{ 
    if (!ispunct(c)) { 
     cout << c; 
    } 
} 

還記得使用大括號以避免歧義。