繁体   English   中英

c语言从字符串中删除字符,出现冲突类型错误

[英]Removing a character from a string in c language, getting conflicting types error

我对编码真的很陌生,并且正在研究从 c 语言中的字符串中删除字符的一个简单的问题。 当我尝试编译我的代码时,我不断收到错误:'remove' 的类型冲突。 我不知道为什么我会收到这个错误,因为代码看起来没问题。 对此的帮助将不胜感激。 这是代码

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

 int main()
{
    char ch,str[30],word[30];
    void remove(char[],char[],char);
    printf("enter the string\n");
    gets(str);
    printf("enter the character to move\n");
    ch=getchar();
    remove(str,word,ch);
    printf("converted to %s\n",word);

}

void remove(char str[], char word[],char c){
int j=0,k=0;
while(str[j++]!='\0'){
if(str[j]!=c)word[k++]=str[j];}
word[k]='\0';

}

头文件<stdio.h>已经有一个名为remove的函数声明。

int remove(const char *filename);

因此编译器会发出错误,因为标识符remove在同一文件范围内以不同类型声明了两次。

因此,将您的函数重命名为例如remove_copy

然而函数实现是错误的。

循环内

while(str[j++]!='\0'){
if(str[j]!=c)word[k++]=str[j];}

由于条件的增加,您正在比较当前后的下一个元素str[j]!=c

str[j++]

该函数可以通过以下方式声明和实现

char * remove_copy( char s1[], const char s2[], char c )
{
    char *p = s1;

    for ( ; *s2; ++s2 )
    {
        if ( *s2 != c ) 
        {
            *p++ = *s2;
        }
    }
    
    *p = '\0';

    return s1;
}  

请注意, gets函数是不安全的,C 标准不再支持该函数。 而是使用标准函数fgets

这是一个演示程序。

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

char * remove_copy( char s1[], const char s2[], char c )
{
    char *p = s1;

    for ( ; *s2; ++s2 )
    {
        if ( *s2 != c ) 
        {
            *p++ = *s2;
        }
    }
    
    *p = '\0';

    return s1;
}  

int main(void) 
{
    enum { N = 30 };
    char str[N], word[N];
    char c;
    
    printf( "Enter a string: " );
    fgets( str, N, stdin );
    
    str[ strcspn( str, "\n" ) ] = '\0';
    
    printf( "Enter a character to remove from the string: " );
    c = getchar();
    
    printf( "The result string is \"%s\"\n", remove_copy( word, str, c ) );
    
    return 0;
}

它的输出可能看起来像

Enter a string: I am learning C++
Enter a character to remove from the string: +
The result string is "I am learning C"
  1. 更改函数名称。 remove被保留
  2. 你的功能无论如何都不起作用
#include <stdio.h>
char *strchrrem(const char *str, char *dest, char c)
{
    char *wrk = dest;
    do
    {
        if(*str != c) *wrk++ = *str;
    }while(*str++);

    return dest;
}

int main(void)
{
    char dest[64];

    printf("%s\n", strchrrem("Hello world.", dest, 'l'));
}

https://godbolt.org/z/exqdE4

暂无
暂无

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

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