如何在while或for循环中使用.find()并且每次都没有给出相同的找到值

时间:2015-07-04 04:12:27

标签: c++

我尝试构建一个经过一段时间或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;
    }

3 个答案:

答案 0 :(得分:1)

我不是100%确定我理解你想要达到的目标。但我可以帮你找到:

它有第二个参数,指定搜索将从字符串开始的位置:

size_t pos = 0;
while ((pos = str.find(' ', pos)) != std::string::npos) {
  std::cout << "Found a space at " << pos << std::endl;
  ++pos;
}

Reference

有关您的代码实际需要的更多信息(显示示例输入和想要的输出),我可以帮助您清除代码的其余部分。
目前,您的描述建议您要输出整个字符串,但要分段(用空格分隔)。

你的代码生成一个(不必要的?)输入副本,生成子字符串只是为了抛弃它们而不返回函数声明中所说的int

如果您想要对输入进行标记,那么this question会为您提供一些答案。

答案 1 :(得分:1)

这是我修复代码的方法:

#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;
}

答案 2 :(得分:1)

您可以使用字符串流。

#include <sstream>
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
    string enteredSentence; // It's initialized to "" by default, by the way
    getline(cin,enteredSentence);
    cout<<"size of sentence: "<<enteredSentence.length()<<endl;
    istringstream str_in(enteredSentence);
    string word;
    while(str_in >> word) {
        // Do stuff with word
        // I believe str_in.str() will also give you the portion that hasn't yet been processed.
    }
    return 0;
}