C++中string的部分字符提取

#include
#include
#include
using namespace std;

int main()
{
vector svec;
string s1("dog cat cat fish");
for (unsigned int i = 0; i != s1.size(); ++i)
{
string s3 = "";
while (s1[i] != ' '&&i < s1.size())
{
s3 += s1[i];
++i;
}
svec.push_back(s3);

    while (s1[i] == ' '&&i < s1.size())
    {
        s3.clear();
    }

}
for (vector<string>::iterator i = svec.begin(); i != svec.end(); ++i)
{
    cout << *i << endl;
}
system("pause");
return 0;

}
我想要分别提取出string:s1中的“dog”,“cat”,“cat”,“fish”;把空格去掉,把这些字符放置在vector中。为什么在vs编程时无法通过,没有数据输出??求解释

i < s1.size() 不是多余的吗?

在push前输出看看

s3.clear();什么意思 清空?需要吗?

string s3 = "";最好定义在for外边。

严禁来说你这样定义 s3只是for块的局部变量。

#include
#include
#include
using namespace std;
int main()
{
vector svec;
string s1("dog cat cat fish");
for (unsigned int i = 0; i <= s1.size(); ++i)
{
string s3 = "";
while (s1[i] != ' '&&i < s1.size())
{
s3 += s1[i];
++i;
}
svec.push_back(s3);

}

vector::iterator it = svec.begin();
for (; it != svec.end(); ++it)
{
cout << (*it).c_str() << endl;
}
//system("pause");
return 0;
}

// i <= s1.size();

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

void Trim(vector<string>& vec, const string& str, const string& token)
{
    size_t flag = 0;
    size_t start = 0;
    string temp;
    while (string::npos != (flag = str.find(token, start)))
    {
        temp = str.substr(start, flag - start);
        vec.push_back(temp);
        start = flag + 1; 
    }
    temp = str.substr(start);
    if (!temp.empty()) { vec.push_back(temp); }
}

int main()
{
    vector<string> svec;
    string s1("dog cat cat fish");
    const string token(" ");
    Trim(svec, s1, token);

    for (vector<string>::const_iterator it = svec.begin(); it != svec.end(); ++it)
    {
        cout << *it << endl;
    }
    return 0;
}

char *strtok(char *str, const char *delim);