Search code examples
carraysstringloopsfgets

fgets outputting weird garbage characters


I'm trying to print a string that fgets takes from keyboard input. But when I run the program I get an endless loop of weird characters. Why?

Here's my code:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define SIZE 6

void stringF();
void revString();
void stringLength();
void verticalString();
void triString();

int main() {
  char string[SIZE];
  stringF(&string[0]);
  system("pause");
  return 0;
}

void stringF(char* str) {
  fgets(str, SIZE, stdin);
  while (str != '\0') {
    putchar(str);
    str++;
  }
}

Solution

  • Rewrite the loop like

    if ( fgets(str, SIZE, stdin) != NULL )
    {
    
       while ( *str != '\0'){
            putchar(*str);
            str++;
        }
    }