在下面的示例中,我想了解为什么将 4195520 的值添加到 chars[2] (计算空格)。
char input;
int chars[4]; // [0] = newlines; [1] = tabs; [2] = spaces; [3] = all_else
int i, j;
printf("--\n");
printf("please enter input\n");
printf("~[enter] to end\n\n");
while ((input = getchar()) != EOF) {
if (input == '\n') {++chars[0];}
else if (input == '\t') {++chars[1];}
else if (input == ' ') {++chars[2];} // 4195520 is added (plus the amount of actual spaces), but only if I add to an array member
// if I increment an integer variable, it counts correctly
else if (input == '~') {printf("\n"); break;}
else {++chars[3];}
}
printf("--\n");
printf("the frequency of different characters\n");
printf("each dot represents one occurance\n");
for (i=0; i<=3; ++i) {
if (i == 0) {printf("newlines:\t");}
else if (i == 1) {printf("tabs:\t\t");}
else if (i == 2) {printf("spaces:\t\t");}
else if (i == 3) {printf("all else:\t");}
for (j=0; j<chars[i]; ++j) {printf(".");} // ~4.2 million dots are printed for spaces
printf("\n");
}
正确计数的解决方案是将数组成员初始化为 0,但我想了解为什么只有空格以及为什么只使用数组成员作为计数器,每次都会递增到数字 4195520。