为什么我在打印计数值之前得到一个新行?

这是我的代码。 这是我想要的输出:

Occurrence of 'l' in Hello world = 3 

但是,在hello world之后,我正在获得一条新线。 我怎么解决这个问题?

 #include #include int main (void){ char first_line[1000]; char second_line[2]; int i,n,j; int count=0,flag=0; fgets(first_line, 1000, stdin); fgets(second_line, 2, stdin); for(i=0; i<strlen(first_line); i++) { if(second_line[0]==first_line[i]) { flag=1; count++; } } if(flag==1) printf("Occurrence of '%c' in %s = %d",second_line[0],first_line,count); else printf("%c isn't present",second_line[0]); return 0; } 

根据C标准中的函数fgets的描述(7.21.7.2 fgets函数)

2 fgets函数最多读取一个小于n指定的字符数,该字符串由stream指向s指向的数组的流指定。 新行字符(保留)或文件结束后不会读取其他字符 。 在读入数组的最后一个字符后立即写入空字符。

例如,要删除新行字符,可以编写

 first_line[ strcspn( first_line, "\n" ) ] = '\0';