gpt4 book ai didi

c - 为什么我在打印计数值之前在这里换行?

转载 作者:太空宇宙 更新时间:2023-11-04 02:30:38 33 4
gpt4 key购买 nike

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

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;
}

最佳答案

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

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.

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

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

关于c - 为什么我在打印计数值之前在这里换行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43789708/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com