C++字母统计程序报错求助:含最长/最短单词统计需求
解决你的C++程序错误与逻辑问题
让我们一步步搞定你遇到的编译错误和代码逻辑问题:
1. 先解决最直接的编译错误
你看到的类型转换错误,核心原因是:你调用myToUpper(word)时,word是char*类型的C字符串,但你的myToUpper函数只接受单个char参数。根据你描述的需求,这个函数本应支持字符和C字符串转大写,所以我们需要给myToUpper添加一个重载版本,让它能处理整个字符串:
修改你的myStrCharFunc.h,添加以下代码(放在单个字符版本的下面):
// 重载版本:将整个C字符串转换为大写 void myToUpper(char cstr[]) { int len = myStrLen(cstr); for (int i = 0; i < len; i++) { // 调用已有的单个字符转大写函数 cstr[i] = myToUpper(cstr[i]); } }
这样你原来的myToUpper(word)调用就合法了。
2. 修复processWord函数的核心逻辑错误
你的processWord现在逻辑完全不对——它遍历所有26个字母,给每个字母的计数都加1,这显然不是你要的“统计每个字母开头的单词次数”。我们需要修改它,只处理当前单词首字母对应的统计项:
替换原有的processWord函数:
void processWord(cstr word, let ar[]) { // 先把单词转大写,统一判断首字母 myToUpper(word); char firstChar = word[0]; // 计算首字母对应的数组索引(A对应0,B对应1...Z对应25) int index = firstChar - 'A'; // 跳过非字母开头的单词(如果输入有这类内容的话) if (index < 0 || index >= SIZE) { return; } // 更新该字母的单词计数 ar[index].count++; int wordLen = myStrLen(word); // 更新最长单词长度 if (wordLen > ar[index].longest) { ar[index].longest = wordLen; } // 更新最短单词长度 if (wordLen < ar[index].shortest) { ar[index].shortest = wordLen; } }
3. 修复其他小问题
(1)readData里的字符数组初始化错误
你写的cstr word=" ";是非法的C++语法,不能直接给字符数组这样赋值。直接声明数组即可,fin>>word会自动读取输入的单词:
cstr word; fin >> word;
(2)readData里的文件错误处理
如果文件打开失败,应该终止程序,避免后续无效操作:
if(!fin) { cout << "Your input file doesn't exist" << endl; exit(EXIT_FAILURE); // 添加这行,需要#include <cstdlib>(你已经加了) }
(3)main函数的逻辑缺失
你的main现在只初始化了数组,没有调用读取数据和输出结果的代码,补充完整:
int main() { let ar[SIZE]; initializeArray(ar); readData(ar); // 输出统计结果 cout << left << setw(10) << "Letter" << setw(10) << "Count" << setw(15) << "Shortest Len" << setw(15) << "Longest Len" << endl; cout << "---------------------------------------------------------" << endl; for (int i = 0; i < SIZE; i++) { // 只输出有单词的字母 if (ar[i].count > 0) { cout << left << setw(10) << (char)('A' + i) << setw(10) << ar[i].count << setw(15) << ar[i].shortest << setw(15) << ar[i].longest << endl; } } return 0; }
(4)代码里的拼写错误
修改struct let里的注释错误:
struct let { int count; // number of words that start with the letter int shortest; int longest; };
最后验证
现在你的代码应该能正常编译运行,读取project2.dat里的内容,统计每个字母开头的单词数量,以及对应最长、最短单词的长度。
内容的提问来源于stack exchange,提问作者That Guy
相关产品推荐
相关产品推荐

