简体   繁体   English

如何比较C中文本的字符?

[英]How to compare a character of a text in C?

I've a simple program that read all the text file characters and during the reading, it excludes some characters. 我有一个简单的程序,读取所有文本文件字符,在阅读过程中,它排除了一些字符。

Here an example to make it clear 这是一个清楚的例子

This is the content of my txt file: 这是我的txt文件的内容:

a b c d e e
f g d h i j 
d d d e e e

I want to remove the character 'd' and the space after it to get this result: 我想删除字符'd'和后面的空格以获得此结果:

a b c e e
f g h i j 
e e e

My program didn't remove the character 'd' and its space after it reads. 我的程序在读取后没有删除字符'd'及其空格。

This is the code I'm using to open and read the txt file: 这是我用来打开和读取txt文件的代码:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) 
{
    if(argc==2)
    {
        FILE *file;
        file = fopen( argv[1], "r" );
        int c;
        char x = ' ';

        if (file == NULL) 
        {
            printf("Error\n");
            return 1;
        }

        while(x != 'd')
        {
            c = fgetc(file);
            if( feof(file) )
            { 
                break ;
            }
            printf("%c", c);
        }

        fclose(file);
    }
    return 0;
}

Just use an if for conditional print. 只需使用if进行条件打印。

Also, make your infinite loops obvious. 另外,让你的无限循环显而易见。

You can skip the space by simply doing an fgetc. 您可以通过简单地执行fgetc来跳过这个空间。

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) 
{
    if(argc==2)
    {
        FILE *file;
        file = fopen( argv[1], "r" );
        int c;

        if (file == NULL) 
        {
            printf("Error\n");
            return 1;
        }

        while((c = fgetc(file)) != EOF)
        {
            if(c == 'd')
            {
                fgetc(file); // Skip space
            }
            else
            {
                printf("%c", c);
            }
        }

        fclose(file);
    }
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM