使用指针按单词反转字符串

Reverse a string by words using pointers

我下面的程序反转字符串,不是按字符而是按单词。

示例输入你好梅洛 样本输出你好梅洛你好

我不知道我从哪里得到第一个问候语。

#include "stdafx.h"
#include <iostream>

int main(int argc, char **argv)
{
  char input[255];
  char *head; // head of a word.
  char *tail; // tail of a word.

  printf("Enter a sentence: ");
  gets_s(input); // read a whole line.
  tail = input + strlen(input) - 1;

  while (tail >= input) 
    {
      if (*tail == 0 || *tail == ' ') 
        {
          tail--; // move to the tail of a word.
        }
      else 
        {
          tail[1] = 0;
          head = tail;
          while (head >= input) 
            {
              if (head == input || *(head - 1) == ' ') 
                {
                  printf("%s",input); // output a word.
                  printf(" ");

                  tail = head - 1; // seek the next word.
                  break;
                }
              head--; // move to the head of a word.
            }
        }
    }

  printf("\n\n");
  system("pause");
  return 0;
}

有人能帮忙吗?

我想你的意思是打印头,而不是输入。您正在从字符串的开头打印,而不是从您刚找到的单词的开头打印。

printf("%s",head); // output a word.