Ana Ferreira
Ana Ferreira

Reputation: 37

Why is my program to reverse its input a line at a time not working?

I was trying to write a program that reverses its input a line at a time. I thought I had done it successfully, however it sometimes doesn't give the desirable output (this happens when I put an input with a smaller length than the one I put previously). I am new to this and I was wondering what can I do to solve this issue.

Program:

#include <stdio.h>
#define MAXLINE 1000

void reverse(char o[], char l[]);
int mgetline(char line[]);

int main(void){
    int len;
    char line[MAXLINE];
    char rev[MAXLINE];

    while((len = mgetline(line)) > 0){
        reverse(rev, line);
        printf("%s\n",rev);
    }
    return 0;
}

int mgetline(char s[])
{
    int c,i;

    for(i = 0; ((c=getchar())!=EOF) && (c!='\n'); ++i)
        s[i] = c;
    if (c == '\n')
    {
        s[i] = c;
        ++i;
    }
    s[i] = '\0';
    return i;
}

void reverse(char revi[], char liner[])
{
    int i, c, j;
    for(i=0;liner[i]!='\0';++i)
    ;
    --i;
    if(liner[i]=='\n')
    --i;

    for(j=0; j<=i ; ++j){
        c = i - j;
        revi[j] = liner[c];
    }
    --j;
}

Upvotes: 0

Views: 57

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311048

The function reverse does not build a string that is it does not append the terminating zero '\0' to the result string.

The second parameter of the function should have the qualifier const because it is not changed in the function.

As all standard C string functions this function should return pointer to the result string.

And it is better to name the function like reverse_copy instead of reverse because the name reverse is usually used when a container is reversed "in place".

It can look the following way

char * reverse_copy( char revi[], const char liner[] )
{
    size_t n = 0;

    while ( liner[n] ) ++n;

    if ( n != 0 && liner[n-1] == '\n' ) --n;

    size_t i = 0;

    while ( n != 0 ) revi[i++] = liner[--n];

    revi[i] = '\0';

    return revi;
}

Upvotes: 0

Eraklon
Eraklon

Reputation: 4288

Since you not terminating the revi string at the end, therefore it will print the leftout characters from the previous result if the new input is smaller. Fix it by adding this

revi[j] = '\0';

at the end of the reverse function and delete that last --j;.

Upvotes: 1

Related Questions