从字符串中删除标点符号

Removing punctuation from string of characters

本文关键字:标点符号 删除 字符串      更新时间:2023-10-16

《C++入门》一书中有一个练习(编号3.2.3),它问道:

编写一个程序,读取包括标点符号在内的字符串,并写出已读取但删除了标点符号的内容。

我试图解决它,但得到了一个错误:

#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;

    }

看看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;
}
int main()
{
    string s;
    cin >> "Enter a sentence : " >> s >> endl;
    for (auto c : s)
        if (ispunct(c))
            remove punct;
    cout << s << endl;
}

您的第一个问题是您使用cin的方式错误。cin用于标准输入,因此尝试打印字符串和换行符是没有意义的。这是cout:的作业

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

另一个问题是remove punct作为一个语句对编译器没有任何意义。这是一个语法错误。由于您希望打印不带标点符号的字符串,因此仅当ispunct()返回false时才打印:

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

还要记住使用大括号以避免歧义。