我正在尝试构建一个经过一会儿或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/

10-09 21:52