【发布时间】:2020-12-08 15:53:44
【问题描述】:
此代码读取输入文本文件,并根据其内容创建输出文件。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define OUT 0
#define IN 1
#define MAX 28
#define BLOCK 4000
/* Check whether the character is alphanumeric */
int isAlphanumeric(char c) {
return ('a' <= c && c <= 'z') ||
('A' <= c && c <= 'Z') ||
('0' <= c && c <= '9');
}
int main(int argc, char *argv[]) {
int c, state = OUT, length = 0, i, j, counter[MAX];
char word[30], longest_word[30];
FILE *input, *output; /* FILE pointers to open the file */
/* Initialize the counter */
for (i = state; i < MAX; i++)
counter[i] = 0;
/* Open the file */
input = fopen("complete_shakespeare.txt", "r");
output = fopen("word_length_histogram.txt", "w");
/* Keep reading the character in the file */
while ((c = getc(input)) != EOF) {
/* If the character is alphanumeric, record it */
if (isAlphanumeric(c)) {
strncat(word, &c, 1);
}
/* If the character is not alphanumeric, increment the corresponding counter, and additionally, record longest word. */
else {
length = strlen(word);
if (length == 27) strcpy(longest_word, word);
counter[length] += 1;
memset(word, 0, sizeof(word));
}
}
/* If the file ends with a word, record its length */
if (isAlphanumeric(word[0])){
length = strlen(word);
counter[length] += 1;
}
/* print the longest word to the file */
fprintf(output, "%s\n\n", longest_word);
/* Make the histogram */
for (i = 1; i < MAX; i++) {
int dividend = counter[i] / 4000 + 1;
fprintf(output, "%2d %6d ", i, counter[i]);
for (j = dividend; j >= 1; j--){
if (counter[i] != 0)
fprintf(output, "*");
}
fprintf(output, "\n");
}
/* Don't forget to close the FILEs */
fclose(input);
fclose(output);
return 0;
}
它会生成正确的输出文件,但是每当我编译它时就会出现这个错误。
B:\CodeBlocks\Projects\Programming in C\hw_4\Homework_4\main.c|44|警告:从不兼容的指针类型 [-Wincompatible-pointer-types] 传递“strncat”的参数 2|
警告似乎来自 strncat 的唯一行。有谁知道如何解决这个问题?
【问题讨论】:
-
不要尝试将字符(或
intwhotsoever)连接到字符串。strncat使用有效的、以 null 结尾的字符串作为两个操作数。 -
你可以尝试根据strncat的定义强制转换参数2 "char * strncat (char * destination, const char * source, size_t num );"第 44 行变为 strncat(word, (const char *) &c, 1);这只会删除警告,如果有任何问题,也不会解决问题。
-
int isAlphanumeric()? Just useisalnum().