我目前正在做一项任务,要求我审查argv的单词和输入重定向。乱码字符串输出
我的问题在我的输出中很明显,可以在下面找到。我有很多跟踪打印语句,可能会或可能不会帮助您指出我的问题。
我的本意是:
- 获取
file.txt
- 的
file.txt
内容复制到buffer[x][y]
,其中[x]
是单词的串并[y]
是[x]
一个字符。 - 将
argv[]
参数与buffer[][]
进行比较。 - 创建
newstr[size2]
。对于buffer[][]
中发现的每个argv[]
争议,请将其替换为replace[9] = "CENSORED"
。 - 打印字符串
newstr[0 to (size2-1)]
。
这里是我的代码:
// censored.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define SIZE 128
int main (int argc, char* argv[])
{
int i = 0;
int j = 0;
int k = 0;
char buffer[SIZE][SIZE];
char x;
int count = 0;
int size1 = sizeof(buffer);
int size2 = 0;
char replace[9] = "CENSORED";
int buffersize=0;
printf("tracing: size1: %d.\n", size1);
printf("tracing: argc: %d.\n", argc);
while((fscanf(stdin, "%c", &x)!=EOF))
{
if(isalpha(x))
{
buffer[i][j]=x;
printf("tracing: buffer[%d][%d]: %c\n", i,j, buffer[i][j]);
j++;
}
else if(isspace(x)) // if whitespace
{
j = 0;
i++;
buffer[i][j]=x;//this should be buffer[i][j]
printf("tracing: buffer[%d][%d]: %c\n", i,j, buffer[i][j]);
j = 0;
i++;
}
else if(ispunct(x)) // if x is a punctuation
{
j = 0;
i++;
buffer[i][j]=x;//this should be buffer[i][j]
printf("tracing: buffer[%d][%d]: %c\n", i,j, buffer[i][j]);
}
else if(iscntrl(x)) // if control key (\n, \r etc...)
{
j = 0;
i++;
buffer[i][j]=x;//this should be buffer[i][j]
printf("tracing: buffer[%d][%d]: %c", i,j, buffer[i][j]);
j = 0;
i++;
}
else if(isdigit(x))
{
buffer[i][j]=x;//this should be buffer[i][j]
printf("tracing: buffer[%d][%d]: %c\n", i,j, buffer[i][j]);
j++;
}
else
{
break;
}
}
size2 = i;
printf("tracing: buffer[8][0]:%s\n",buffer[8]);
char newstr[size2][SIZE];
i = 0;
j = 0;
// tracing:
printf("tracing: line 72\n");
printf("tracing: size2: %d.\n", size2);
while(i < size2) //print buffer[]
{
printf("%s", buffer[i]);
i++;
}
printf("tracing: line 80\n");
for(k=1; k < argc; k++)
{
printf("%s\n", argv[k]);
}
// end tracing
i = 0; //reinitialize i
j = 0; //reinitialize j
// creating newstr[SIZE] and censoring words
printf("tracing: line 89\n");
for(i = 0; i < size2; i++)
{
for(j=1; j < argc; j++)
{
if(strcmp(buffer[i], argv[j])==0)
{
strcpy(newstr[i], &replace[0]);
printf("tracing: replaced at [%d]\n", i);
break;
}
else
{
strcpy(newstr[i], buffer[i]);
printf("tracing: copied at [%d]\n", i);
}
}
}
i = 0; //reinitialize i
while(i < size2)
{
printf("%s", newstr[i]);
i++;
}
return 0;
}
假设我已经输入重定向文件名为file.txt
及其内容:
Said Hamlet to Ophelia,
I'll draw a sketch of thee,
What kind of pencil shall I use?
2B or not 2B?
我输入的是:
./censored Ophelia thee 2B < file.txt
这是我得到的奇怪的输出:
Said Hamlet to CENSORED, Ill draw a sketch ???)ofoQ? ?"h?CENSORED,2oQ?
What? /oQ?kind? of 6oQ?pencil +oQ?shall ?"h?I-oQ? ???)use? ???2BoQ?
7oQoroQ Qnot 1oQ?CENSORED?4oQ?
任何帮助表示赞赏,我知道我的代码是凌乱的,这是我的第一个学期的学习C.
您的.txt文件明确以Ascii格式显示,对不对? – Magisch
'buffer [i]'不是NUL终止的。尝试更改'char buffer [SIZE] [SIZE];'char char [SIZE] [SIZE] = {'\ 0'};' –
@magisch是的,它是 – noobcoder