【发布时间】:2021-12-15 15:21:48
【问题描述】:
我的目标是编写一个函数,计算重定向文本文件中所有唯一字符的数量(意思是直到达到 EOF)。我写的代码:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define ASCII_VALS 128
int strLen (char inp[])
{
int len = 0;
for(int i = 0; inp[i] != '\0'; i++){
len++;
}
return len;
}
int countUniqueChars (char inp[])
{
int everyCharValArr[ASCII_VALS] = {0};
int i, j = 0;
for(i = 0; i < strLen(inp); i++){
int convToInt = inp[i] - '0';
everyCharValArr[convToInt] = 1;
}
for (i = 0; i < ASCII_VALS; i++) {
j += everyCharValArr[i];
}
return j;
}
适用于通过scanf() 输入的一个字符串,如下所示:
int main ()
{
char inp[100];
printf("Enter a string: \n");
scanf("%99s", inp);
printf("%d\n", countUniqueChars(inp));
return 0;
}
但是在我更改主要功能后读取重定向的文本文件,像这样:
int main ()
{
char inp[100];
int total = 0;
while(fgets(inp, 100, stdin)){
total += countUniqueChars(inp);
}
printf("%d\n", total);
return 0;
}
并在 input.txt 文件上运行程序 (./binary <input.txt),其内容如下:
Toydolls
Flies
trees
rocks
things
值变成26,正确(1. word = 6 unique chars, 2. word = 5 unique chars, 3 .word = 4 unique chars, 4. word = 5, 5. word = 6 unique chars),但显然不考虑出现在更多行上的考虑字符,根本不应计为唯一字符。我的问题是如何修复函数来完成此任务?
【问题讨论】:
-
当
convToInt超出范围 [0...128) 时,everyCharValArr[convToInt]会出现问题。 -
“计算标准输入中所有唯一字符的数量。” --> 是只计算输入的 1 行 还是直到
stdin返回EOF? -
@chux-ReinstateMonica 这意味着直到标准输入返回 EOF,抱歉没有早点说明。已编辑问题。
-
第一个单词实际上有 6 个唯一字符,这将使总和
26所以你得到的输出是正确的。 -
您的数组
int everyCharValArr[ASCII_VALS] = {0};存在每个输入行,并随着每个新行重置。你需要让它在两行之间持续存在。有几种方法可以做到这一点,我会让你尝试找出一种。