0

I have to make a program in c that accepts one word with no spaces and prints out each letter on a new line. However, I have to use fgets. I wrote this program:

#include <stdio.h>
#define MAX_LINE 4096

int main(void) {
    int i;
    char array[MAX_LINE];

    printf("Enter a string: ");
    fgets(array,MAX_LINE,stdin);
        for(i=0; array[i]!='\0'; i++){  
            printf("%c\n",array[i]);

       }
       return 0;
}

But it keeps printing out an extra 2 lines at the end of the word. I don't understand why.

2 Answers2

1

fgets reads in the newline character into the buffer if there's enough space in the buffer. You can modify the condition to accommodate that:

for(i=0; array[i] != '\n' && array[i] != '\0'; i++) {

man fgets:

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.

P.P
  • 117,907
  • 20
  • 175
  • 238
0

fgets reads the newline and store it in the buffer.

See also here: Removing trailing newline character from fgets() input

Igal S.
  • 13,146
  • 5
  • 30
  • 48