2017-08-09 72 views
-1

我正在编写一个代码,它将从stdin中检查一个单词和一个文本,并在文本中出现时检查该单词。这是我的代码,但是当我编译代码时,它会在下面产生错误。从一个没有强制转换的指针中产生整数

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

int main(int argc, char* argv[]) 
{ 
    char censor[] = "CENSORED"; 
    char input[1028]; 

    for(int i = 1; i < argc; i++){ 
     if(strstr(input, argv[i]) != NULL){ 
      for(int j = 0; j < strlen(input); j++){ 
       if(strcmp(input[j], argv[i]) == 0){ 
        input[j] = censor; 
       } 
      } 
     } 
    } 

    printf("%s", input); 
    printf("\n"); 
} 

censored.c:在函数 '主':censored.c:13:15:警告:传递 参数 '的strcmp' 的1时将整数指针,未作铸造 [-Wint转换] if(strcmp(input [j],argv [i])== 0){censored.c:3:0中包含的文件:/usr/include/string.h:140:12:note:预期'const char *',但 参数的类型为'char'extern int strcmp(const char * __ s1,const char * __ s2) ^ censored.c:14:15:warning: [-Wint-conversion] input [j] = censor;

我不确定他们为什么认为char数组是一个整数,请大家帮忙,谢谢!

+2

'输入[J]'装置选择第j个字符出来的阵列。所以你传递的是单个字符,而不是数组。我想你的意思是'input + j' –

+0

'strstr(input,argv [i])!= NULL'使用未初始化的字符串? –

+0

'strcmp'的参数是'const char * str1,const char * str2',你只在输入[j]中使用了一个字符' – Tisp

回答

0

如音符在你的错误何况你是路过的,而不是为const char *, 注焦炭:预计 '为const char *',但参数的类型为 '字符' 的extern INT STRCMP

这里字符输入[1028] ;是字符数组。所以你需要传递数组索引的地址,例如&输入[j]而不是输入[j]。

STRCMP(&输入[J],argv的[1])应在工作的地方

STRCMP(输入[J],ARGV [I])

注意:这里的argv [i]是char *数组,所以你不需要传递它作为& argv [i]。另外在数组的情况下,如果你提到数组索引,那么你需要添加&来传递它的地址。如果你正在传递数组而不提及索引ie在你的情况strcmp(输入,argv [i])然后它会通过输入地址[0]

1

由于错误提示,有两个问题s在你的代码中。

  1. 在线路13:输入[J]是一个字符,我们应该通过字符*像&输入[J]或(输入+ j)的或输入。

  2. 在第14行中:您不能通过“=”将一个字符串直接复制到其他字符串中。

您可以参考下面的代码为您的功能。

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
int main(int argc, char* argv[]) 
{ 
    char censor[] = "CENSORED"; 
    char word[] = "bad_word"; 
    char input[1028]; 
    /* added logic code */ 
    for(int i = 1; i < argc; i++) { 
      /* compare if this is bad word */ 
      if(strcmp(argv[i], word) == 0) { 
        // found bad_word 
        //replace with censor 
        strcat(input, censor); 
        strcat(input, " "); 
      } else { 
        // no bad word, we can go with the same 
        strcat(input, argv[i]); 
        strcat(input, " "); 
      } 
    } 
    printf("%s", input); 
    printf("\n"); 
} 

所以运行从终端您的代码作为

./a.out I found bad_word and this is bad_word 

,它会给输出作为

I found CENSORED and this is CENSORED 
相关问题