我正在尝试编写一个程序,该程序将接受用户的输入,然后在单独的行上打印句子中的每个单词。下面的代码有效,只是它缺少输入的任何句子中的最后一个单词。我没有在这个片段中包含标题。谁能告诉我这是为什么?
int main()
{
//Declare variables
string userSentence = " ";
string permanantUserSentence = " ";
int spaceNumber = 0;
int wordNumber = 0;
int characterCount = 0;
int reverseCount = 0;
int posLastSpace = -1;
int posSpace = 0;
//Begin the loop
while(userSentence != "quit" && userSentence != "q")
{
//Prompt the user for their sentence
cout << "Enter command: ";
getline(cin, userSentence);
permanantUserSentence = userSentence;
//Condition to make sure values are not calculated and printed for the quit conditions
if(userSentence != "quit" && userSentence != "q")
{
//Print each word in the string separately by finding where the spaces are
int posLastSpace = -1;
int posSpace = userSentence.find(" ", posLastSpace + 1);
while(posSpace != -1)
{
cout << "expression is: " << userSentence.substr( posLastSpace+ 1, posSpace - posLastSpace - 1) << endl;
posLastSpace = posSpace;
//Find the next space
posSpace = userSentence.find(" ", posLastSpace + 1);
}
//Clear the input buffer and start a new line before the next iteration
cout << endl;
}
}
}