gpt4 book ai didi

c++ - 如何使用嵌套的 getline() 函数来获取字符串中的特殊字符和标点符号?

转载 作者:行者123 更新时间:2023-11-28 00:54:24 27 4
gpt4 key购买 nike

我正在使用 getline() 函数来获取句子中的特殊字符和标点符号,这样当我显示句子中包含的单词时,它除了 a-z(或 A-Z)之外没有任何其他字符。问题是它变长了,我不认为它真的有效。我想知道我是否可以有效地做到这一点。我正在使用 Dev-C++,下面的代码是用 C++ 编写的。感谢您的帮助。

#include <string>
#include <iostream>
#include <ctype.h>
#include <sstream>

using namespace std;



int main()
{
int i=0;
char y;
string prose, word, word1, word2;
cout << "Enter a sentence: ";
getline(cin, prose);

string mot;
stringstream ss(prose);


y=prose[i++];
if (y=' ') // if character space is encoutered...


cout<<endl << "list of words in the prose " << endl;
cout << "---------------------------"<<endl;
while(getline(ss, word, y)) //remove the space...
{

stringstream ss1(word);

while(getline(ss1, word1, ',')) //remove the comma...
{

stringstream ss2(word1); //remove the period
while(getline(ss2, word2, '.'))
cout<< word2 <<endl; //and display just the word without space, comma or period.
}
}


cout<<'\n';
system ("Pause");
return 0;
}
#############################输出

输入一句话:什么?当我说:“妮可,把我的拖鞋拿来,给我y night-cap,”这是散文吗?

散文中的单词列表

什么?什么时候我说:“妮可带来我我的拖鞋和给我我的睡帽“是那散文?

按任意键继续。 . .

最佳答案

使用std::remove_if() :

std::string s(":;[{abcd 8239234");

s.erase(std::remove_if(s.begin(),
s.end(),
[](const char c) { return !isalpha(c); }),
s.end());

如果您没有 C++11 编译器,请定义谓词而不是使用 lambda(在线演示 http://ideone.com/NvhKq)。

关于c++ - 如何使用嵌套的 getline() 函数来获取字符串中的特殊字符和标点符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12383690/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com