【问题标题】:Censoring words found in STDIN and printing to STDOUT not working审查在 STDIN 中找到的单词并打印到 STDOUT 不起作用
【发布时间】:2017-03-28 06:50:12
【问题描述】:

我的程序应该采用任意数量的单字文本字符串参数,每个参数长度小于 128 个字符。它将任何文本从标准输入复制到标准输出,除了输入中看到的任何单词都被单词 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();
}
}

【问题讨论】:

  • 欢迎来到 Stack Overflow!听起来您可能需要学习如何使用debugger 来单步执行您的代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。进一步阅读:How to debug small programs.
  • 你说它有效,你需要什么样的修复?请编辑您的问题并描述问题。

标签: c arrays printing c-strings


【解决方案1】:

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

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

到:

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

另一个问题,可能是您注意到的,是您没有初始化found。制作它:

        int found = 0;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多