Abhinav Jain Abhinav Jain - 15 days ago 7
C Question

Printf Not Working in Ubuntu

So I was required to write a program that reverses its input a line at a time and this is what I basically came up with:

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

#define MAXLINE 1000

int getLine(char s[], int lim)
{
int c, i;
for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
s[i] = c;
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}

int reverse(char line[], char reverse[])
{
int i, j;
for (i = 0, j = strlen(line); i < strlen(line); i++, j--) {
reverse[i] = line[j];
}
return 0;
}

int main()
{
int len;
char line[MAXLINE];
char rev[MAXLINE];
while (len = getLine(line, MAXLINE) > 0) {
reverse(line, rev);
printf("%s\n", rev);
}
return 0;
}


As far as I know it's fine and should work correctly but when I run it even though the next line gets printed there is no reversed string there!
Same problem persists in other programs as well where I need to print a string, I am not sure if I should ask the question on
askubuntu
forum or here so I gave it a shot here first!

Jay Jay
Answer

In the reverse function, you miss copying the '\0' character. This might be causing the printf to not print the string. Please do remember that strlen gives length without the '\0'.

Modified Reverse function should be like this:

int reverse(char line[], char reverse[])
{
        int i, j;
        for (i = 0, j = (strlen(line)-1); i < strlen(line); i++, j--) {
                reverse[i] = line[j];
        }
        reverse[i] = '\0'
        return 0;
}