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

标签 c++

我正在尝试构建一个函数,该函数通过 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/

相关文章:

c# - 将非托管类型结构指针转换为托管类型结构指针

c++ - 抽象接口(interface)继承

c++ - 派生类更改基类的复制构造函数

c++ - CMake RelWithDebInfo 链接到调试库

c++ - boost::stable_vector 的 capacity 成员函数不返回分配的容量

c++ - 从qt进度条中删除文本

c++ - 无法使用 visual studio 导出 C++ dll

c++: X 类没有名为 Y 的成员

C++ 继承和初始化顺序

c++ - 如何在现有的 qtabwidget 中添加子选项卡?