书中C++ Primer (编号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;
}
答案 0 :(得分: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;
}
答案 1 :(得分:2)
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;
}
}
还记得使用大括号来避免含糊不清。