assassin
assassin

Reputation: 1

Trying to reverse a string but adds an extra character when less than 4 characters are taken as input

This is the code I am not able to fix it. It works fine if 5 or more characters are used but using less than 4 characters breaks it.

#include <stdio.h>
void main()
{
    char str[1000], rev[1000];
    int i, j, count = 0;
    printf("Enter the string :");
    scanf("%s", str);
    printf("\nString Before Reverse: %s", str);
    while (str[count] != '\0')
    {
        count++;
    }
    j = count-1 ;
    for (i = 0; i<count; i++)
    {
        rev[i] = str[j];
        j--;
    }
    printf("\nString After Reverse: %s", rev);
}

Upvotes: 0

Views: 107

Answers (1)

Vens8
Vens8

Reputation: 85

Your have to null terminate your rev string like:

rev[count] = '\0';

Also, please make your code more readable.

Upvotes: 1

Related Questions