我有以下源代码来计算文件中的空格、新行和字符:
#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
字符数正确(包括空格和换行)。但是为什么变量b
和nl
的结果是错误的呢?
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++;
}
这应该可以解决问题。
我是一名优秀的程序员,十分优秀!