如何删除句子中的所有标点符号? 我是C++新手,正在尝试解决初学者从句子中删除所有标点符号的问题。下面是我想出的代码。但是,当我输入“Hello!Hello!”时,编译器输出“Hello”而不是“Hello Hello”(这是我所期望的)

如何删除句子中的所有标点符号? 我是C++新手,正在尝试解决初学者从句子中删除所有标点符号的问题。下面是我想出的代码。但是,当我输入“Hello!Hello!”时,编译器输出“Hello”而不是“Hello Hello”(这是我所期望的),c++,cin,C++,Cin,为什么会这样 #include <iostream> #include <string> using namespace std; int main(){ cout << "please enter a sentence which include one or more punctuation marks" << endl; string userInput; string result; cin &g

为什么会这样

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

int main(){

    cout << "please enter a sentence which include one or more punctuation marks" << endl;    
    string userInput;
    string result;
    cin >> userInput;
    decltype(userInput.size()) n;
    for (n = 0; n < userInput.size(); n++){
        if(!ispunct(userInput[n])){
            result += userInput[n];
            cout << result << endl;
        }
    }
    return 0;
}
编译器输出:

Hello

执行用户输入时,它最多只能读取输入流中的第一个空格字符


您可能想改用
std::getline
(默认情况下,它将读取整行)。

尝试使用
getline()
函数。读一读


欢迎来到C++!阅读关于他们非常擅长处理字符串的文章

正如其他人所说,您可以使用
getline
阅读整行文本

我还想指出,
中有函数

#包括
#包括
#包括
int main()
{
std::字符串行;
while(std::getline(std::cin,line))
{
line.erase(std::remove_if(line.begin()、line.end()、ispunt)、line.end());

std::非常感谢你们的建议!非常感谢!有你们这样的人帮助初学者真是太棒了!考虑到他正在从
userInput
复制到
result
std::如果
可能更适合的话,请删除复制。
Hello
#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    std::string line;
    while( std::getline( std::cin, line ) )
    {
        line.erase( std::remove_if( line.begin(), line.end(), ispunct ), line.end() );
        std::cout << line << std::endl;
    }
    return 0;
}