简体   繁体   English

审查在STDIN中找到的单词并打印到STDOUT不起作用

[英]Censoring words found in STDIN and printing to STDOUT not working

My program is supposed to take any number of one-word text string arguments, each less than 128 characters long. 我的程序应该采用任意数量的单字文本字符串参数,每个参数的长度小于128个字符。 It copies any text from stdin to stdout, except that any of the words seen in the input are replaced with the word CENSORED. 它将任何文本从stdin复制到stdout,除了输入中出现的任何单词都替换为CENSORED之外。 So far it kinda works. 到目前为止,它仍然有效。 Any ideas on how I can fix it? 关于如何解决的任何想法?

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

int main(int argc, char* argv[]){
char word[128];
int index = 0;
int c = getchar();

while (c != EOF){
    //checks for letter and adds to word[]
    if ((c>='A' && c<='Z') || (c>='a' && c<='z') || c == '\''){
        word[index] = (char)c;
        index++;
        word[index] = '\0';
    }
    //when c is not a letter or ' (end of word)
    else{ 
        if (index > 0){
            int found;
            for (int i=1;i<argc;i++){
                //if word[] is found in input censor it
                if (strcmp(word,argv[i]) == 0){
                    printf("CENSORED");
                    found = 1;
                    break;
                }
            }
            //prints word[] if it's not in input
            if (found != 1){
                printf("%s",word);
            }

        }
        //resets word[] and index / prints value of c
        word[0] = '\0';
        index = 0;
        printf("%c",(char)c);
    }
    //increment c
    c = getchar();
}
}

I see two problems. 我看到两个问题。 First, you should not be overflowing your buffer if you do get a word >127 characters. 首先,如果您得到的单词大于127个字符,则不应使缓冲区溢出。 Change: 更改:

    word[index] = (char)c;
    index++;

to: 至:

    if ( index+1 < sizeof(word) ) {
        word[index] = (char)c;
        index++;
    }

The other problem, likely the one you have noticed, is that you aren't initializing found . 另一个问题,可能是您已经注意到的一个问题,是您没有初始化found Make it: 做了:

        int found = 0;

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

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