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

时间:2017-05-04 17:54:01

标签: c string printf

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

Occurrence of 'l' in Hello world = 3

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

#include<stdio.h>
#include<string.h>
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;
}

1 个答案:

答案 0 :(得分:2)

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

  

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

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

first_line[ strcspn( first_line, "\n" ) ] = '\0';
相关问题