gpt4 book ai didi

c++ - 我如何在一段时间或 for 循环中使用 .find() 并且每次都没有给出相同的发现值

转载 作者:行者123 更新时间:2023-11-28 00:14:33 26 4
gpt4 key购买 nike

我正在尝试构建一个函数,该函数通过 while 或 for 循环并找到空格的位置,输出空格之前的所有内容,然后删除空格之前的所有内容,包括空格,然后再次重复此操作。

非常感谢任何帮助。

int sentence()
{
string enteredSentence="";

getline(cin,enteredSentence);
string sentenceString(enteredSentence);

int sentenceLength=enteredSentence.size();
cout<<"size of sentence"<<sentenceLength<<endl;
int stringSize=sentenceString.size();
while(stringSize>0)
{
int spaceLoc = enteredSentence.find(" ");
cout<<spaceLoc;

cout<<sentenceString.substr(0,spaceLoc)<<endl;
sentenceString.substr(0,spaceLoc);
cout<<"string before string eraced"<<sentenceString<<endl;

sentenceString.erase (0,spaceLoc);
cout<<"string after string eraced"<<sentenceString<<endl;

stringSize=sentenceString.size();
cout<<"string size is"<<stringSize<<endl;
}

最佳答案

我就是这样修复你的代码的:

#include <iostream>

using namespace std;

int main()
{
string enteredSentence="";

getline(cin,enteredSentence);
string sentenceString(enteredSentence);

int sentenceLength = enteredSentence.size();
cout<<"size of sentence:"<<sentenceLength<<endl;
string::size_type stringSize = sentenceString.size();
while(stringSize > 0)
{
int spaceLoc = sentenceString.find(" "); //there was incorrect var
cout<<spaceLoc<<endl;

if(spaceLoc == string::npos){
cout<<"last part:"<<sentenceString<<endl;
break;
}//check if there are no spaces left

cout<<sentenceString.substr(0,spaceLoc)<<endl;
//the substr line here was redundant
cout<<"string before string erased:"<<sentenceString<<endl;

sentenceString.erase(0, spaceLoc + 1);//also delete the space
cout<<"string after string erased:"<<sentenceString<<endl;

stringSize=sentenceString.size();
cout<<"string size:"<<stringSize<<endl<<endl;

}
return 0;
}

关于c++ - 我如何在一段时间或 for 循环中使用 .find() 并且每次都没有给出相同的发现值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31216797/

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