【发布时间】:2020-04-30 18:01:15
【问题描述】:
目前我正在制作一个使用具有空元素的char 数组的项目。我希望能够获得数组的长度,就非空元素的数量而言。这似乎相当微不足道,我做了这个函数:
int getWordLen(char word[]) {
int count = 0;
for (int i = 0; i < 512; i++) {
if (word[i] != '\0') {
count++;
}
}
printf("%d ", count);
return count;
}
但是,每个 char 数组都返回 188 的长度。任何帮助将不胜感激。
这是我调用它的函数:
void redact(Words * redactWords, char fileName[]) {
FILE * file = fopen(fileName, "r");
FILE * outputFile = fopen("outputFile.txt", "w+");
char word[512];
int i = 0;
char c;
while (c != EOF) {
c = getc(file);
if ((c > 96) && (c < 123)) {
word[i] = c;
i++;
continue;
}
else if ((c > 64) && (c < 91)) {
word[i] = c + 32;
i++;
continue;
}
i = 0;
if (isWordRedactWord(redactWords, word)) {
//write stars to file
char starStr[512];
for (int i = 0; i < getWordLen(word); i++) {
starStr[i] = '*';
}
fputs(starStr, outputFile);
}
else {
//write word to file
fputs(word, outputFile);
}
strcpy(word, emptyWord(word));
}
fclose(file);
fclose(outputFile);
}
【问题讨论】:
-
你能补充一下你是如何调用这个函数的吗?
-
\0后面可能有字符。 -
也许是零初始化?
char word[512] = ""; -
请勿使用
char与EOF进行比较。 必须是int。 -
while (c != EOF) { c = getc(file); ...->while ((c = getc(file)) != EOF) { ...