Reputation: 311
I am attempting to write a program that will accept an input from the user and then print each one of the words in the sentence on a separate line. The code below works except it is missing the last word in any sentence that is input. I did not include the header in this snippet. Can anyone tell me why this is?
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;
}
}
}
Upvotes: 0
Views: 124
Reputation: 2272
You are not printing the remainder of your input when you exit your while loop.
The end of the sentence generally won't have any spaces after it. So your while loop exits with some remainder (the last word and whatever follows). Therefore, you need to print the remainder of your input out to print out the word.
Upvotes: 2