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

标签 c arrays printing c-strings

我的程序应该采用任意数量的单字文本字符串参数,每个参数的长度小于 128 个字符。它将所有文本从 stdin 复制到 stdout,但输入中看到的任何单词都会被单词 CENSORED 替换。到目前为止还算有效。关于如何修复它有什么想法吗?

#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();
}
}

最佳答案

我看到两个问题。首先,如果您确实收到超过 127 个字符的单词,则不应溢出缓冲区。变化:

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

至:

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

另一个问题(可能是您已经注意到的问题)是您没有初始化 found。做到:

        int found = 0;

关于审查 STDIN 中找到的单词并打印到 STDOUT 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43062511/

相关文章:

定期调用已创建线程的函数(手动调度)

c - 不同的打印输出(C程序)

Javascript 数组不会更新

c - 斐波那契和数组返回

python - 循环每个元素并根据该元素打印 word2vec 向量

在C中将字节数组/字符数组转换为十六进制字符串

c - 在 C 代码中解压 .xz 文件

javascript - Array.prototype.reduce() 在一个元素的数组上

c++ - 如何打印 std::atomic<unsigned int> 的值?

ios - 在 iOS 上通过蓝牙打印