2016-08-20 105 views
2

我正在尝试制作一个C++程序,它接收用户输入并提取字符串中的单个单词,例如, “你好,鲍勃”会得到“你好”,“对”,“鲍勃”。最终,我将把它们推入一个字符串向量中。这是我尝试在设计代码时要使用的格式:从字符串中提取单个单词C++

//string libraries and all other appropriate libraries have been included above here 
string UserInput; 
getline(cin,UserInput) 
vector<string> words; 
string temp=UserInput; 
string pushBackVar;//this will eventually be used to pushback words into a vector 
for (int i=0;i<UserInput.length();i++) 
{ 
    if(UserInput[i]==32) 
    { 
    pushBackVar=temp.erase(i,UserInput.length()-i); 
    //something like words.pushback(pushBackVar) will go here; 
    } 
} 

但是,如果有任何空格的话(例如,如果我们在此之前只在string.It遇到的第一个空间的作品不工作有“你好我的世界”,pushBackVar将在第一个循环后成为“Hello”,然后是第二个循环后的“Hello my”,当我想要“Hello”和“我的”时)。我该如何解决这个问题?有没有其他更好的方法来从字符串中提取单个单词?我希望我没有困惑任何人。

+1

的可能的复制(http://stackoverflow.com/questions/236129/split-a-string-in-c) –

回答

1

Split a string in C++?

#include <string> 
#include <sstream> 
#include <vector> 

using namespace std; 

void split(const string &s, char delim, vector<string> &elems) { 
    stringstream ss(s); 
    string item; 
    while (getline(ss, item, delim)) { 
     elems.push_back(item); 
    } 
} 


vector<string> split(const string &s, char delim) { 
    vector<string> elems; 
    split(s, delim, elems); 
    return elems; 
} 

所以你的情况只是做:

words = split(temp,' '); 
+0

你应该引用它,但我不确定。 – Rakete1111

1
#include <algorithm>  // std::(copy) 
#include <iostream>   // std::(cin, cout) 
#include <iterator>   // std::(istream_iterator, back_inserter) 
#include <sstream>   // std::(istringstream) 
#include <string>   // std::(string) 
#include <vector>   // std::(vector) 
using namespace std; 

auto main() 
    -> int 
{ 
    string user_input; 
    getline(cin, user_input); 
    vector<string> words; 
    { 
     istringstream input_as_stream(user_input); 
     copy(
      istream_iterator<string>(input_as_stream), 
      istream_iterator<string>(), 
      back_inserter(words) 
      ); 
    } 

    for(string const& word : words) 
    { 
     cout << word << '\n'; 
    } 
} 
0

可以使用运营商直接>>到microbuffer(串)中提取的单词。 (getline不需要)。看看下面的功能:?在拆分C++字符串]

vector<string> Extract(const string& stoextract) { 
    vector<string> aListofWords; 
    stringstream sstoext(stoextract); 
    string sWordBuf; 

    while (sstoext >> sWordBuf) 
     aListofWords.push_back(sWordBuf); 

    return aListofWords; 
} 
相关问题