-1

In this program, I'm trying to input a sentence and print the sentence in reverse order. Like for example, if my input is "I Like You", then my output must be "You Like I". Please help me fix this code!

#include<stdio.h>
#include<string.h>

void words(char arr[], int n)
{
    for(int i=n-1; i>=0; i--)
    {
       if(arr[i]==' ')
       {
           arr[i]='\0';
           printf("%s ", &(arr[i])+1);
       }
    }
    printf("%s", arr);
}

int main()
{
    char x[50];
    printf("Enter the sentence: ");
    gets(x);

    int size=strlen(x);

    void words(x, size);
    return 0;
}

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1) dont use `gets()`: it is dangerous because it doesn't provide any control capability on the size of data received in input, possibly causing crashes. 2) For your task you might find useful checking out [strcmp](https://linux.die.net/man/3/strcmp). – Roberto Caboni Apr 16 '20 at 20:23
  • 4
    Are you trying to actually *sort* the words, or just print them in reverse order? – Caleb Apr 16 '20 at 20:27

1 Answers1

1

Just remove void form line 22 change void words(x, size); to words(x, size);:

#include<stdio.h>
#include<string.h>

void words(char arr[], int n)
{
    for(int i=n-1; i>=0; i--)
    {
       if(arr[i]==' ')
       {
           arr[i]='\0';
           printf("%s ", &(arr[i])+1);
       }
    }
    printf("%s", arr);
}

int main()
{
    char x[50];
    printf("Enter the sentence: ");
    //gets(x);
    scanf("%[^\n]s",x);

    int size=strlen(x);

    words(x, size);
    return 0;
}

Output:

Enter the sentence: i like you                                                                                        
you like i

Note: You should not use gets() due to some security reasons. For reference why not use gets()? visit this:

Why is the gets function so dangerous that it should not be used?

Sheri
  • 1,383
  • 3
  • 10
  • 26