1

Why is this printing one empty line at the beginning of the output? \n is only after %s... Help please, I'm so frustrated.

if(argc > 1){

    while(r!=NULL){

        r = fgets(str, MAXL, stdin);

        if(r==NULL){
            return 0;
        }

        if (*argv[1] == 'i'){
            char *invP = inv(r);
            printf("%s\n", invP);
            free(invP);
        }

inv() is:

char* inv(char* C){
int length = 0;

int i;
for(i = 0; C[i]!='\0'; i++){
    length++;
}

char *inverted;
inverted = malloc(length+1);
inverted[length] = '\0';
char* invP = inverted;

int j = 0;
for(i = length - 1; i >= 0; i--){
    inverted[j] = C[i];
    j++;
}
return invP;
}

It doesn't have any print on it, dunno why is this happening.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Punk
  • 11
  • 4

1 Answers1

7

When you call fgets, your r string has a newline at the end. So, when you invert it (by calling inv), the string ends up with the newline at the beginning. Then, when you print it, you see the newline first.

r -> "hello\n"
invP = "\nolleh"

If you want to remove the newline, you can use something like

char *pos;
if ((pos=strchr(r, '\n')) != NULL)
    *pos = '\0';

(taken from here)

Community
  • 1
  • 1
Xymostech
  • 9,710
  • 3
  • 34
  • 44
  • Xymostech You're ABSOLUTELY right! I can't use strlib in this project, so I fixed it in my inv() method by switching for(i = 0; C[i]!='\0'; i++){ for for(i = 0; C[i]!='\n'; i++){ Thank you very much I was going crazy!! – Punk Mar 24 '13 at 21:50