簡體   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