Andrew Andrew - 1 month ago 16
C Question

Why is the a new line in the printf output?

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

int main(void){

char noun[25];
char plural[28];

fgets(noun,24,stdin);
strcpy(plural,noun);
int len=strlen(plural);

if(plural[len-2]=='h'||plural[len-2]=='s'){
plural[len-1]='e';
plural[len]='s';
plural[len+1]='\0';
}else if(plural[len-2]=='y'){
plural[len-2]='i';
plural[len-1]='e';
plural[len]='s';
plural[len+1]='\0';
}else{
plural[len-1]='s';
plural[len]='\0';
}

printf("The plural of noun %s is %s\n",noun,plural);
return 0;
}


the output is always this:

"The plural of noun horse

is horses"

even though i do not put \n the middle of the printf, only in the end.

Answer

fgets is picking up a trailing newline character from stdin when you hit enter. Hence noun ends with a newline char