从用户输入的字符串中删除标点符号
Removal of the punctuation from strings given as an input by the user
正在看《C Primer 5th edition》这本书,书里问了这个问题,问题题是3.10。
所以,基本上我们必须删除标点符号,如果它们存在于我们要提供的字符串中。
我已经尝试过这个问题,甚至在我预先初始化字符串时也得到了成功的输出。这是我的代码,在代码执行之前初始化了字符串:
代码:
#include <bits/stdc++.h>
#include <string>
using namespace std;
int main()
{
string s("he@@,llo world...!!@");
for(auto &c:s)
{
if(ispunct(c))
{
cout<<"";
}
else
cout<<c;
}
return 0;
}
此特定代码提供了正确的输出,即 hello world。
现在,如果我尝试使用相同的代码格式,但条件是用户必须提供字符串作为输入,那么代码不会给出正确的输出,它只会忽略其余部分空格后的字符串。
我试过的代码是:
#include <bits/stdc++.h>
#include <string>
using namespace std;
int main()
{
string s;
cin>>s;
for(auto &c:s)
{
if(ispunct(c))
{
cout<<"";
}
else
cout<<c;
}
return 0;
}
在代码执行期间,当我将字符串输入为 he@@,llo world...!!@
该代码为我提供了输出:hello。忽略空格后的下一部分字符串。
嗯,我的问题是,
Why does this code doesn't works when the string is taken as the form
of input by the user? And what can I do to make the code work without
any errors?
修改建议:
一位社区成员提供的当前建议没有回答我的问题,因为它不是关于从用户那里获取输入并将输入格式化为文件,而这里提出的问题是关于删除标点符号和字符并在用户提供输入时打印字符串的其余部分。
标准cin >>
只获取一行中的第一个“单词”;单词通常由 space 分隔,这就是为什么忽略 he@@,llo
之后 space 之后的所有内容。您需要使用的是 getline(cin, s)
来捕获整行。
正在看《C Primer 5th edition》这本书,书里问了这个问题,问题题是3.10。 所以,基本上我们必须删除标点符号,如果它们存在于我们要提供的字符串中。 我已经尝试过这个问题,甚至在我预先初始化字符串时也得到了成功的输出。这是我的代码,在代码执行之前初始化了字符串:
代码:
#include <bits/stdc++.h>
#include <string>
using namespace std;
int main()
{
string s("he@@,llo world...!!@");
for(auto &c:s)
{
if(ispunct(c))
{
cout<<"";
}
else
cout<<c;
}
return 0;
}
此特定代码提供了正确的输出,即 hello world。
现在,如果我尝试使用相同的代码格式,但条件是用户必须提供字符串作为输入,那么代码不会给出正确的输出,它只会忽略其余部分空格后的字符串。
我试过的代码是:
#include <bits/stdc++.h>
#include <string>
using namespace std;
int main()
{
string s;
cin>>s;
for(auto &c:s)
{
if(ispunct(c))
{
cout<<"";
}
else
cout<<c;
}
return 0;
}
在代码执行期间,当我将字符串输入为 he@@,llo world...!!@ 该代码为我提供了输出:hello。忽略空格后的下一部分字符串。
嗯,我的问题是,
Why does this code doesn't works when the string is taken as the form of input by the user? And what can I do to make the code work without any errors?
修改建议: 一位社区成员提供的当前建议没有回答我的问题,因为它不是关于从用户那里获取输入并将输入格式化为文件,而这里提出的问题是关于删除标点符号和字符并在用户提供输入时打印字符串的其余部分。
标准cin >>
只获取一行中的第一个“单词”;单词通常由 space 分隔,这就是为什么忽略 he@@,llo
之后 space 之后的所有内容。您需要使用的是 getline(cin, s)
来捕获整行。