C++ 为什么我在运行这个循环以打印字符串中的每个单词时缺少一个值?

C++ 为什么我在运行这个循环以打印字符串中的每个单词时缺少一个值?,c++,string,loops,C++,String,Loops,我正在尝试编写一个程序,接受用户的输入,然后将句子中的每个单词打印在单独的一行上。下面的代码除了在输入的任何句子中缺少最后一个单词外都有效。我没有在这个片段中包含标题。谁能告诉我这是为什么 int main() { //Declare variables string userSentence = " "; string permanantUserSentence = " "; int spaceNumber = 0; int wordNumber = 0

我正在尝试编写一个程序,接受用户的输入,然后将句子中的每个单词打印在单独的一行上。下面的代码除了在输入的任何句子中缺少最后一个单词外都有效。我没有在这个片段中包含标题。谁能告诉我这是为什么

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;
        }
    }
}
intmain()
{
//声明变量
字符串user句子=”;
字符串permanantUser句子=”;
int spaceNumber=0;
int-wordNumber=0;
int characterCount=0;
int reverseCount=0;
int posLastSpace=-1;
int posSpace=0;
//开始循环
while(user句子!=“退出”&&user句子!=“q”)
{
//提示用户输入他们的句子

cout退出while循环时,您没有打印其余的输入


句子的结尾通常不会有空格,因此while循环会带一些余数(最后一个单词和后面的任何内容)退出。因此,您需要打印出输入的其余部分以打印出单词。

您似乎在寻找一个空格来分隔单词,但最后一个单词后面没有空格。确实如此。我在嵌套的while循环末尾添加了一个if语句,它打印出了正确的值。