Search code examples
cstringreversewords

a program to reverse each word in a string( ive read the previous solutions but im looking for one using the functions i only here


i've wrote this c program but im always receiving the same inputed sentence as an output without any change! i've split every word in the string and then reversed their position but it didnt work well! any solutions please!

#include<stdio.h>
#include<conio.h>
#include<string.h>
int main ()
{    
    char A[81][81];
    int t=0,j=1,k=0,l;
    puts("Input a sentence (max 80 character)");
    gets(A[0]);
    while (A[0][t]!='\0')
    {
        if(A[0][t]=='\32')
        {
            j++;
            t++;
            k=0;
        }
        A[j][k]=A[0][t];
        k++;
        t++;
    }
    for (l=j;l>0;l--)
    {
        printf("%s",A[l]);
    }
    getch();
}

Solution

  • #include <stdio.h>
    #include <string.h>
    #include <conio.h>
    
    int main(void){ 
        char A[81][81] = {0};
        int t=0,j=1,k=0,l;
        puts("Input a sentence (max 80 character)");
        scanf("%80[^\n]", A[0]);//'gets' has already been abolished, it should explore a different way.
        while (A[0][t] != '\0'){
            if(A[0][t] == ' '){
                ++j;
                k=0;
                while(A[0][t] == ' ')//Skip spaces
                    ++t;
            } else {
                A[j][k++] = A[0][t++];
            }
        }
        for (l=j;l>0;l--){
            printf(" %s",A[l]);
        }
        puts("");
        getch();
    }