【发布时间】:2023-03-24 04:50:01
【问题描述】:
我需要一些帮助来制作一个将句子分成单词的函数,这个函数应该适用于不同长度的句子。
这里是示例代码:
void spilt_sentence(string sentence)
{}
int main()
{
std::string sentence1= "Hello everyone";
std::string sentence2= "Hello I am doing stuff";
split_sentence(sentence1);
split_sentence(sentence2);
return 0;
}
我看到有人使用 std::istringstream 来获取每个空格之前的每个单词,但我真的不知道它是如何工作的。当我输入 std::istringstream ss(sentence); 时,它给了我错误在代码中。另外,我正在使用 c++98 并使用 cygwin 编译我的程序。有什么线索吗?谢谢。
编辑:该函数将根据句子中有多少单词创建许多变量。
编辑:我实际上正在开发一个 LinkedList 程序,我在这里要做的是将句子拆分为单词,然后生成包含每个单词的新节点。
这是实际代码(注意:我对其进行了一些修改,因此它与我的实际代码不完全相同。而且我没有为 Node 使用结构),假设第 1 句是“大家好”,第 2 句是“你好,我在做事”。
The expected output will be:
linkedlist1:
"hello"<->"everyone"
linkedlist2:
"hello"<->"I"<->"am"<->"doing"<->"stuff"
LinkedList.cpp 内:
void LinkedList::add(std::string sentence)
{
//breaks down the sentence into words
std::istringstream ss(sentence);
do
{
std::string word;
ss >> word;
//store them in nodes in a linkedlist
Node* new_tail = new Node(word);
if (size == 0)
{
head = new_tail;
tail = new_tail;
}
else
{
new_tail->set_previous(tail);
tail->set_next(new_tail);
tail = new_tail;
}
new_tail = NULL;
size++;
}
while(ss);
}
[已修复]编译时弹出错误消息,说 std::istringstream ss 有默认设置但类型不完整。我该怎么办?
【问题讨论】:
-
嗨有趣,也许这个答案可能会引起兴趣stackoverflow.com/questions/236129/…
-
@IronMan 感谢您的快速回复。我正在看它。一旦我弄清楚了,我会更新代码。
-
欢迎来到Stack Overflow。从您提供的不完整代码中,无法确定代码的确切问题。请提供minimal reproducible example 以证明您遇到的错误。
-
抱歉,我不太擅长从我正在开发的程序中制作示例。我会稍微修改一下实际程序的代码,然后在帖子中展示。