我正在寻求帮助,在代码中读取包含标点符号的字符串,并输出用省略标点符号读取的内容。我访问了这个链接C++ Remove punctuation from String,我相信我的代码是可靠的。当我编译代码时,它会提示输入字符串。然而,在输入字符串并按enter之后,什么都没有发生
int main(){
string line;
cout <<"Please Enter a line"<< endl;
while(getline(cin, line)){
for(decltype(line.size()) index = 0; index != line.size() && !isspace(line[index]); ++index){
if (ispunct(line[index])){
line.erase(index--,1);
line[index] = line.size();
}
}
}
cout<< line << endl;
return 0;
}
发布于 2015-02-16 02:52:44
你让这条路变得更复杂了(decltype
?为了这个?)比它所需要的要多。尝试:
int main()
{
std::string line;
std::cout <<"Please Enter a line"<< std::endl;
while(std::getline(std::cin, line)){
const char* s = line.c_str();
while(*s){
if (!ispunct(*s)){
std::cout << *s; // not as slow as you would think: buffered output
}
++s;
}
std::cout << std::endl; // flush stdout, that buffering thing
}
}
更简单通常更好。作为一个额外的奖励,这也应该是相当快一些。
发布于 2015-02-16 03:25:58
这可以在没有循环的情况下完成。使用算法函数是您所需要的。
通常,如果您有一个容器,并且您希望从满足某种条件的容器中删除项,那么如果您正在编写手工编码的循环,那么您将使用一种长的(可能是错误的)方法。
下面是一个使用算法函数的示例,即std::remove_if
。
#include <algorithm>
#include <cctype>
#include <string>
#include <iostream>
using namespace std;
int main()
{
std::string s = "This is, a, string: with ! punctuation.;";
s.erase(std::remove_if(s.begin(), s.end(), ::ispunct), s.end());
cout << s;
}
发布于 2015-02-16 03:17:34
您的代码没有输出任何东西的原因是因为它被困在getline循环中。
假设c++11:
int main(){
string line;
cout <<"Please Enter a line"<< endl;
getline(cin, line);
line.erase(std::remove_if(line.begin(), line.end(),
[](char ch) { return ispunct(ch) ? true : false; }), line.end());
cout << line << endl;
return 0;
}
或
int main(){
string line;
cout <<"Please Enter a line"<< endl;
transform(line.begin(), line.end(), line.begin(),
[](char ch) { return ispunct(ch) ? '\0' : ch; });
cout << line << endl;
return 0;
}
https://stackoverflow.com/questions/28533819
复制相似问题