这是我当前尝试运行的代码片段:
int main()
{
//Declare variables
string userSentence = " ";
string permanantUserSentence = " ";
int spaceNumber = 0;
int wordNumber = 0;
int characterCount = 0;
int reverseCount = 1;
int posLastSpace = -1;
int posSpace = 0;
int reverseSpace = 0;
int previousReverseSpace = 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")
{
//Find and print all of the words in reverse order
cout << "\nIn Reverse Order: ";
for(reverseCount = userSentence.length() - 1; reverseCount >= 0; reverseCount -= 1)
{
if(userSentence.substr(reverseCount, 1) == " ")
{
cout << userSentence.substr(reverseCount, userSentence.length() - reverseCount);
}
}
//Clear the input buffer and start a new line before the next iteration
cout << endl;
这样做的目的是从用户那里获取一个名为 userSentence 的字符串,然后按照给出的相反顺序将每个单词打印给用户。例如,“小心!” 会变成“out!看”。运行此代码时,它不会为字符串的反转版本返回任何内容。