簡體   English   中英

C:不計算空格和新線

[英]C: Not counting spaces and new lines

我有以下源代碼來計算文件中的空格,換行符和字符:

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

那應該解決這個問題。

#include<stdio.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h> // or just include <string> it may vary depending on the compiler you use
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(strcasecmp(ch, " ") == 0) //you need to use strcasecmp() instead of == for strings
b++;
if(ch[0] == '\n') //you can also check like this.
nl++;
c++;
}
printf("no of blanks %d\n", b);
printf("no of new line %d\n", nl);
printf("no of characters %d\n", c);
}

嘗試將空格" "和換行符"\\n"放在單引號中,並將ch聲明為char

我沒有測試你的代碼,但乍看之下我發現了一個錯誤:

char ch[1]; 

您正在使用只有一個char的數組。 你應該只使用一個角色:

char ch;

為什么? 因為當你測試時:

if(ch==' ')
    b++;
if(ch=='\n')
    nl++;

您正在傳遞數組的起始地址。 如果你還想使用數組,你應該測試ch [0],如果你想使用char,你應該測試ch。 您還要將字符串與字符串進行比較:字符用簡單的引號括起來。 雙引號用於字符串。 即使你在字符串中有一個“”字符,它仍然被認為是一個字符串。 采用 ' '。

在C語言中,您無法直接比較兩個字符串。 您必須使用strcmp(char * str1,char * str2)或strncmp(char * str1,char * str2,ssize_t size)。

如果你將直接比較字符串,它將返回0,這就是為什么空格和換行不遞增。

試試這個修正。

#include<stdio.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
int main()
{
 int fdesc;
 int blanks=0, newlines=0, characters=0;
 char buf[1];
 fdesc=open("text.txt", O_RDONLY);
 while((read(fdesc,buf, 1))>0)
 {
  if(strcmp(buf," "))
   blanks++;
  if(strcmp(buf,"\n"))
   newlines++;
  characters++;
 }
 printf("no of blanks %d\n", blanks);
 printf("no of new line %d\n", newlines);
 printf("no of characters %d\n", characters);
}

感謝您的反饋,我設法修復了代碼,最后看起來像這樣:

#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[0]==' ')
b++;
if(ch[0]=='\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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM