我试图在C++中使用向量在单个单词中分割字符串。所以我想知道如何忽略向量中的空格,如果用户在字符串中的单词之间放置多个空格。忽略向量中的空格C++
我该怎么做?
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
cout<<"Sentence: ";
string sentence;
getline(cin,sentence);
vector<string> my;
int start=0;
unsigned int end=sentence.size();
unsigned int temp=0;
while(temp<end){
int te=sentence.find(" ",start);
temp=te;
my.push_back(sentence.substr(start, temp-start));
start=temp+1;
}
unsigned int i;
for(i=0 ; i<my.size() ; i++){
cout<<my[i]<<endl;
}
return 0;
}
也许用'的std :: regex'甚至更好'的std :: stringstream'。 – Ron
为什么不简单地使用'cin >> string'并迭代? –
我会正确缩进代码,以便帮助人们更清晰。 – s5s