0
//Write a program in c language to accept a string and reverse it without using strrev function of string.
#include <stdio.h>
#include <conio.h>
int main()
{
    int i, len = 0;
    char text[100], continue1;
    clrscr();
    do
    {
        printf("\nWrite the text to get its reverse: ");
        gets(text);
        for (i = 0; text[i] != NULL; i++)
            len = len + 1;
        printf("\nLength of string is %d\n", len);
        printf("Reverse of entered text is ");

        //reverse part
        while (len >= 0)
        {
            printf("%c", text[len]);
            len--;
        }
        printf("\npress y for continue or press any other key to exit: ");
        scanf(" %c", &continue1);
    } while (continue1 == 'y');
    printf("\nThanking You");
    return 0;
    getch();
}

it's creating problem only in case of y means when program get repeat 2nd time. If I enter any other character as input then it's print last part and program get finished. The following result is shown on console.

Write the text to get its reverse: abc
Length of string is 3
Reverse of entered text is cba
press y for continue or press any other key to exit: y

Write the text to get its reverse:
Length of string is -1
Reverse of entered text is
press y for continue or press any other key to exit:
Suraj
  • 91
  • 1
  • 7
  • 1
    You are entering `"Y\n"`. The `scanf` reads the `Y` and leaves `\n`. Then `gets` is called, reads the `\n` and immediately returns. – kaylum Apr 29 '21 at 04:48
  • 1
    OT: [Why is the gets function so dangerous that it should not be used?](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) – kaylum Apr 29 '21 at 04:49
  • to build on what's been said, `gets` replaces the newline with a NUL terminator `'\0'`, so `text[0]==0`. This skips your `for` loop. Furthermore, `len == -1` from the previous iteration, so the `while` loop is skipped as well; you need to reinitialize `len` to 0 at the beginning of each loop. Also, `text[i] != NULL` is a comparison between an integer and pointer, best to make that `text[i] != '\0'`. – yano Apr 29 '21 at 04:56
  • @kaylum why the same is not happening in case of integer. It's work properly when we use " %c" in last input for continue or not(in case of integer as input initially). – Suraj Apr 29 '21 at 12:53
  • Read the answers in the duplicate post. That is explained. `%d` skips whitespaces including `\n`. `gets` does not. – kaylum Apr 29 '21 at 12:55

0 Answers0