我正在尝试制作一个接收用户输入并提取字符串中的单个单词的 C++ 程序,例如“Hello to Bob”会得到“Hello”、“to”、“Bob”。最终,我会将这些推入字符串向量中。这是我在设计代码时尝试使用的格式:
//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;
}
}
但是,这只适用于字符串中遇到的第一个空格。如果单词之前有任何空格(例如,如果我们有“Hello my World”,pushBackVar 在第一个循环后将是“Hello”,然后在第二个循环之后,当我想要“Hello”和“my”时,“Hello my”。)我该如何解决这个问题?还有其他更好的方法可以从字符串中提取单个单词吗?我希望我没有让任何人感到困惑。
原文由 VVSTITAN 发布,翻译遵循 CC BY-SA 4.0 许可协议
请参阅 在 C++ 中拆分字符串?
因此,在您的情况下,只需执行以下操作: