Jude
Jude

Reputation: 451

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++;
  }
}

Upvotes: 2

Views: 1811

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311018

Rewrite the loop like

if ( fgets(str, SIZE, stdin) != NULL )
{

   while ( *str != '\0'){
        putchar(*str);
        str++;
    }
}

Upvotes: 3

Related Questions