C:不计算空格和新线

时间:2016-05-29 11:22:30

标签: 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

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

6 个答案:

答案 0 :(得分:2)

  

if(ch ==&#34;&#34;)

应该是

  

if(ch ==&#39;&#39;)

对于其他比较,"\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++;
}

这应该可以解决问题。

答案 1 :(得分:1)

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

答案 2 :(得分:0)

尝试将空格" "和换行符"\n"放在单引号中,并将ch声明为char

答案 3 :(得分:0)

我没有测试你的代码,但乍看之下我发现了一个错误:

char ch[1]; 

您正在使用只有一个char的数组。你应该只使用一个角色:

char ch;

为什么呢? 因为在你测试的时候:

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

您正在传递数组的起始地址。如果你还想使用数组,你应该测试ch [0],如果你想使用char,你应该测试ch。 您还要将字符串与字符串进行比较:字符用简单的引号括起来。双引号用于字符串。 即使你有&#34; &#34;字符串中的一个字符,仍然被认为是一个字符串。使用&#39; &#39;

答案 4 :(得分:0)

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

答案 5 :(得分:0)

感谢您的反馈,我设法修复了代码,最后看起来像是:

#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);
}
相关问题