gpt4 book ai didi

c++ - 我想从一个字符串句子中取出单词并在 C++ 中得到这个错误

转载 作者:行者123 更新时间:2023-11-28 00:46:20 25 4
gpt4 key购买 nike

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

void extractFirstWord(string& sentence, string& word);
void processBlanks(string& sentence);

int main() {
string sentence, word;
cout << "Input a sentence: ";
getline(cin, sentence);

while (sentence != "") {
processBlanks(sentence); // removes all blanks from the front of sentence
if (sentence.length() > 0) { // removing blanks may have made sentence null - cannot extract from a null string
extractFirstWord(sentence, word); // gets first word from sentence and puts into word
cout << word << endl; // output one word at a time
}
}

system("PAUSE");
return 0;
}

void extractFirstWord(string& sentence, string& word)
{
int i=0;
while(sentence[i]!=' ')
{
i++;
}
word=sentence.substr(0,i);
sentence=sentence.substr(i);
}
// extractFirstWord removes the substring of sentence
// from the beginning to the first space from sentence
// and stores the same string into word. sentence is
// shortened accordingly.
// Postcondition: sentence is shortened, and word
// is appropriately the first word in
// sentence.

void processBlanks(string& sentence)
{
int i=0;
while(sentence[i]==' '){i++;}
sentence=sentence.substr(i);
}

processBlanks 将删除句子前面的所有空格。后置条件:句子第一个词前没有空格。

我想从一个字符串句子中取出单词并在c++中得到这个错误

错误是 -> 字符串下标超出范围

最佳答案

extractFirstWord 中,如果您还没有找到空格,您会不断增加 i。但是,如果它是字符串中的最后一个单词,您可能会索引到字符串的末尾。像这样更改 while 条件:

while(i < sentence.length() && sentence[i]!=' ')

关于c++ - 我想从一个字符串句子中取出单词并在 C++ 中得到这个错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16131759/

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