我正在为学校编写一个程序,要求从文件中读取文本,将所有内容大写,并删除标点和空格。文件“Congress.txt”包含以下内容:
(Congress shall make no law respecting an establishment of religion, or prohibiting the free exercise thereof; or abridging the freedom of speech, or of the press; or the right of the people peaceably to assemble, and to petition the government for a redress of grievances.)
尽管我已经成功读取了文件,但是我现在遇到了一些问题,即如何去除标点、空格并使所有字母大写,因为这可能会导致垃圾字符出现。我目前的代码如下:
(Congress shall make no law respecting an establishment of religion, or prohibiting the free exercise thereof; or abridging the freedom of speech, or of the press; or the right of the people peaceably to assemble, and to petition the government for a redress of grievances.)
尽管我已经成功读取了文件,但是我现在遇到了一些问题,即如何去除标点、空格并使所有字母大写,因为这可能会导致垃圾字符出现。我目前的代码如下:
void processFile(char line[]) {
FILE *fp;
int i = 0;
char c;
if (!(fp = fopen("congress.txt", "r"))) {
printf("File could not be opened for input.\n");
exit(1);
}
line[i] = '\0';
fseek(fp, 0, SEEK_END);
fseek(fp, 0, SEEK_SET);
for (i = 0; i < MAX; ++i) {
fscanf(fp, "%c", &line[i]);
if (line[i] == ' ')
i++;
else if (ispunct((unsigned char)line[i]))
i++;
else if (islower((unsigned char)line[i])) {
line[i] = toupper((unsigned char)line[i]);
i++;
}
printf("%c", line[i]);
fprintf(csis, "%c", line[i]);
}
fclose(fp);
}
我不知道这是否是一个问题,但我定义了MAX为272,因为文本文件包含标点符号和空格。
我得到的输出是:
C╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠Press any key to continue . . .
i
进行两次递增操作。你只需要在将内容复制到数组中时递增i
。退出循环前(无论如何)应该对字符串进行空终止处理。 - Jonathan Leffleri
,不需要在其他地方修改它。 - Zoltánwhile ((c = getc(fp)) != EOF)
的循环形式,并且只有在执行赋值操作时才会对i
进行递增。 - Jonathan Leffler