我正在尝试制作一个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”和“我的”时)。我该如何解决这个问题?有没有其他更好的方法来从字符串中提取单个单词?我希望我没有困惑任何人。
的可能的复制(http://stackoverflow.com/questions/236129/split-a-string-in-c) –