-1

I am currently learning C, and I want to create a function that reverses an input. Here is the piece of code I wrote:

#include <stdio.h>

int main(int argc, char** argv) {
char input[100];

while(1) {
    fgets(input, 100, stdin);

        for(int i = 99; i > -1; i--) {
            printf("%c", input[i]);
        }

    printf("\n");
    }
}

The output of this is correct, but it also prints some garbage in between and I don't understand why. Can someone explain this to me?

This is the output:

enter image description here

FatimahFatCakes
  • 331
  • 1
  • 3
  • 11
  • 1
    Rather than starting from `i = 99`, you have to figure out how many characters you got and start from that amount - 1. – HolyBlackCat Mar 24 '19 at 07:42
  • Possible duplicate of [What is the default value of a char in an uninitialized array, in C?](https://stackoverflow.com/questions/24797860/what-is-the-default-value-of-a-char-in-an-uninitialized-array-in-c) – dandan78 Mar 24 '19 at 08:13

2 Answers2

1

Firstly, you should clear memory before using it.

Secondly, always keep one char with 'NULL' value at the end of a string. (only an option for your case, because you are not using sprintf, strcpy... and so on.)

Thirdly the for loop should start at the end of the input, that is strlen(input) which is located on <string.h>

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

int main(int argc, char** argv) {
char input[100];

while(1) {
    memset(input, 0, sizeof(input));    // add memset() to clear memory before using it
    fgets(input, 100, stdin);

    for(int i = strlen(input); i > -1; i--) {
        printf("%c", input[i]);
    }

    printf("\n");
    }
}
C. Tatu
  • 33
  • 2
  • 8
Yuanhui
  • 459
  • 5
  • 15
1

Yuanhui explained it pretty good, so I'll just provide some improvement on his code:

int main() { // No need for argc and argv unless you use them
char input[100] = {0}; // Simpler than memset

do {
    // Security risk if you decide to change the size of input, so use
    // sizeof input instead of hard coded value. Also, check return value.
    if(!fgets(input, sizeof input, stdin)) { /* Error handling code */ }

    // Overkill to use printf for a single char
    for(int i = strlen(input); i > -1; i--) putchar(input[i]);
    putchar('\n');
} while(!feof(stdin)) // End the loop on EOF
}
klutt
  • 30,332
  • 17
  • 55
  • 95