在STDIN中发现的审查单词和打印到STDOUT不起作用
问题描述:
我的程序应该采用任意数量的单字文本字符串参数,每个字符长度不超过128个字符。它将stdin中的任何文本复制到标准输出中,除了输入中看到的任何单词都用单词CENSORED替换。到目前为止它有点作品。关于如何修复它的任何想法?在STDIN中发现的审查单词和打印到STDOUT不起作用
#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;
欢迎来到堆栈溢出!这听起来像你可能需要学习如何使用[调试器](https://en.wikipedia.org/wiki/Debugger)来遍历你的代码。使用一个好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏离的位置。如果你打算做任何编程,这是一个重要的工具。进一步阅读:[如何调试小程序](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。 –
你说它有效,你需要什么样的修复?请编辑你的问题并描述问题。 –