fputs() producing wrong result

226 views Asked by At

My code is producing incorrect result. I don't know why.

When I give the length as 5 and enter the string as "vasanth", this should produce "vasan" as output. But it gives output as "vasa".

#include<stdio.h>
#include<conio.h>

int main(){
    int n;
    printf("Enter the length of the string : ");
    scanf("%d", &n);
    getchar();
    char array[n];
    fgets(array, n, stdin);
    fputs(array, stdout);
    return 0;
}
1

There are 1 answers

0
MikeCAT On

The last element is reserved for a terminating null-character. Allocate one more element to fix.

#include<stdio.h>

int main(void){
    int n;
    printf("Enter the length of the string : ");
    scanf("%d", &n);
    getchar();
    char array[n+1];
    fgets(array, n+1, stdin);
    fputs(array, stdout);
    return 0;
}

Quote from N1570 7.21.7.2 The fgets function:

2 The fgets function reads at most one less than the number of characters specified by n from the stream pointed to by stream into the array pointed to by s. No additional characters are read after a new-line character (which is retained) or after end-of-file. A null character is written immediately after the last character read into the array.

Here you will find that the number of characters to read is at most one less than the specified n.