gpt4 book ai didi

c - 文件阅读-C类(class)作业题

转载 作者:行者123 更新时间:2023-12-01 06:14:57 24 4
gpt4 key购买 nike

我正在学习 C 编程的入门类(class)并有这项作业。

Write a program that reads in a regular text file as input and outputs how many of each letter appeared in that file.

以下是我目前所拥有的。问题是它什么都不输出,我不知道该怎么做。我意识到在 while 循环中没有有效的表达式。我在那里放了一个占位符“TEST”,因为我不确定当它到达文件末尾时要测试什么。有什么想法吗?

#include <stdio.h>

int main() {
int i, index, chars[256];
char letter;
FILE *ifp;

//sets the value of all the counters to 0
for (i = 0; i < 256; i++)
chars[i] = 0;

ifp = fopen("input.txt", "r");

//loops through reading each character and then increments the counter by 1
while (TEST) {
fscanf(ifp, "%c", &letter);
index = letter;
chars[index] += 1;
}

//prints the totals for each character
for (i = 0; i < 256; i++) {
letter = i;
printf("%c: %d\n", letter, chars[i]);
}

fclose(ifp);

return 0;
}

最佳答案

有点偏离轨道。与可能实现的非常简洁的代码相比,这将构成一个 if 丛林。

这篇文章假设您使用 ASCII 编码,这应该是正确的,除非您使用一个非常奇怪的系统。

我有两三个提示给你。首先,数组是将值组合在一起的好工具。

其次,字符实际上是整数,你可以从字母中减去字母。

char letter = 'z';
int index = letter - 'a'; // gives 25

您可能还对 isalpha 感兴趣功能。

关于c - 文件阅读-C类(class)作业题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6560329/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com