gpt4 book ai didi

C:不计算空格和换行

转载 作者:太空宇宙 更新时间:2023-11-04 01:54:08 27 4
gpt4 key购买 nike

我有以下源代码来计算文件中的空格、新行和字符:

#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(){
int fd;
int b=0, nl=0, c=0;
char ch[1];
fd=open("text.txt", O_RDONLY);

while((read(fd, ch, 1))>0)
{
if(ch==" ")
b++;
if(ch=="\n")
nl++;
c++;
}
printf("no of blanks %d\n", b);
printf("no of new line %d\n", nl);
printf("no of characters %d\n", c);
}

结果是这样的:

no of blanks 0
no of new line 0
no of characters 24

我的 text.txt 文件的内容是:

hello world
hello
world

字符数正确(包括空格和换行)。但是为什么变量bnl的结果是错误的呢?
PS:我是 C 的新手,但在 C++ 方面有一些练习。

最佳答案

if(ch==" ")

应该是

if(ch==' ')

和其他比较一样,"\n" 应该是 '\n'

双引号是字符串。字符使用单引号。

是的,您应该使用 fopen 而不是低级别的 open 调用。

int ch;
FILE *fp=fopen("text.txt", "r");

while((ch = getc(fp)) != EOF)
{
if(ch==' ')
b++;
if(ch=='\n')
nl++;
c++;
}

这应该可以解决问题。

关于C:不计算空格和换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37509289/

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