#include <stdio.h>
#include <ctype.h>
void readFile(FILE *file);
void count (FILE *file, int *alpha, int *digit, int *punct, int *spaces);
void printMessage(int *alpha, int *digit, int *punct, int *spaces);
int main( void ) {
FILE *file = NULL;
readFile(file);
return 0;
}
void readFile(FILE *file) {
file = fopen("/Users/AdmiralDanny/Desktop/testFile.txt", "r");
int *alpha = NULL, *digit = NULL, *punct = NULL, *space = NULL;
if (file) {
count(file, alpha, digit, punct, space);
fclose(file);
} else {
perror( "error opening the file" );
}
}
void count (FILE *file, int *alpha, int *digit, int *punct, int *spaces) {
int ch;
while ((ch = fgetc(file)) != EOF ) {
if (isalpha(ch) != 0) {
++alpha;
} else if (isdigit(ch)) {
++digit;
} else if (ispunct(ch)) {
++punct;
} else if (isspace(ch)) {
++spaces;
}
}
printMessage(alpha, digit, punct, spaces);
}
void printMessage(int *alpha, int *digit, int *punct, int *spaces) {
printf( "alphabetic characters: %d\n", alpha );
printf( "digit characters: %d\n", digit);
printf( "punctuation characters: %d\n", punct );
printf( "whitespace characters: %d\n", spaces );
}
我的 .txt 文件只有 4 个空格和 12 个字母字符,但它给了我 48 个字母字符和 8 个空白字符?为什么会这样? 另外,当我尝试在 printMessage 方法中打印出 int pointeres 时收到警告
最佳答案
没有为任何 int
分配内存,count()
函数只是递增 int
指针而不是 int
值:
++spaces; /* spaces is an int* so this increments the pointer. */
您可以使用 malloc()
,但堆栈分配和传递地址会更简单。
int alpha = 0, digit = 0, punct = 0, space = 0;
count(file, &alpha, &digit, &punct, &space);
在 count()
中:
(*spaces)++;
取消引用 int
用于递增和取消引用打印:
printf( "whitespace characters: %d\n", *spaces);
由于 count()
的调用者不需要 int
的更新值,只需按值传递而完全忘记指针(与 相同) printMessage()
).
关于带有 int 指针的转换代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11806503/