Iファイルに空白、改行文字をカウントする次のソースコードを持っている:C:数えていないスペースや改行
#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++で少し練習しています。
'(、CH、FD(1を読んで))> 0 'あなたがしているように見えます情報を捨てる –
'char ch [1];'は奇妙に見えます。おそらくちょうど 'char ch;' – pzaenger
最小の修正は 'ch [0] == '''と 'ch [0] == '\ n''または' 'ch =='' 'と' * ch – alk