为什么我在打印计数值之前在这里得到一个新行? [英] Why am I getting a new line here before print count value?
问题描述
这是我的代码.这是我想要的输出:
Here's my code. Here's my desired output:
Occurrence of 'l' in Hello world = 3
但是我在 hello world 之后得到了一条新线路.我该如何解决这个问题?
But I am getting a new line after hello world. How I can fix this?
#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;
}
推荐答案
根据C标准中fgets
函数的描述(7.21.7.2 fgets函数)
According to the description of the function fgets
in the C Standard (7.21.7.2 The fgets function)
2 fgets 函数读取最多比读取的数量少 1由流指向的流中的 n 指定的字符s 指向的数组.在 a 之后不会读取额外的字符换行符(保留) 或在文件结束之后.一个空字符在读入的最后一个字符后立即写入数组.
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.
要删除换行符,您可以编写例如
To remove the new line character you can write for example
first_line[ strcspn( first_line, "\n" ) ] = '\0';
这篇关于为什么我在打印计数值之前在这里得到一个新行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!