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;
        }
    }
}
4

1 回答 1

2

退出 while 循环时,您不会打印输入的其余部分。

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

于 2013-11-14T00:33:41.557 回答