问题描述
您可以在此处看到代码分为三部分。主要部分和关键部分询问我发现行号和单词号。但是当我调用第三部分(即letter_frequency函数)时,该部分不会出现在控制台中。我看了无数个地方,但没有找到答复。如果没有太多麻烦的答复,我会从中获利的。
预期输出:
输入您的字符串: 嘿丽莎
你好吗#
输入具有2行,7个单词和以下字母频率: A:2 B:0 C:0 ...像这样
立即输出:
输入您的字符串: 嘿丽莎
你好吗#
输入有2行,7个单词和以下字母频率:
#include <iostream>
#include<cmath>
#include<math.h>
#include<iomanip>
#include<string>
#include<cstring>
void letter_frequency(char le[]);
int main()
{
char str[400] = " ";
int words = 1;
int lines = 1;
cout << "Enter Your String : ";
cin.get(*str);
while (*str != '#')
{
cin.get(*str);
if (*str == ' ' || *str == '\n')
words++;
if (*str == '\n')
lines++;
}
cout << "The input has " << lines << " lines," << words
<< " words," << " and the following letter frequencies : \n";
letter_frequency(str);
return 0;
}
void letter_frequency(char le[])
{
//for Capitals
int sum = 0;
for (int i = 65; i <= 95; i++)
{
sum = 0;
for (int j = 0; j < sizeof(le); j++)
{
if ( (int)le[j] == i)
{
sum = sum + 1;
}
}
if (sum > 0)
{
cout << (char)i << ": " << sum << "\t" << endl;
}
}
//For Small
for (int i = 97; i <= 122; i++)
{
sum = 0;
for (int j = 0; j < sizeof(le); j++)
{
if ( (int)le[j] == i)
{
sum = sum + 1;
}
}
if (sum > 0)
{
cout << (char)i << ": " << sum << "\t" << endl;
}
}
}
解决方法
首先,除非您被教授强迫使用原始的char
数组作为学习练习,否则您肯定应该使用std::string
。
第二,在不深入研究代码是否真正履行其承诺的前提下,我怀疑您遇到的主要错误是在for循环中:
for(int j=0; j<sizeof(le); j++)
问题在于le
的类型为char[]
,没有大小,这是char*
的另一种说法。因此,使用sizeof
运算符实际上会返回char*
的大小,该大小可能始终为4或8,具体取决于目标体系结构。您需要做的是:
- 使用
std::string
,然后调用length()
函数(首选选项)。 - 使用字符串传递大小,例如,进行签名:
void letter_frequency(const char le[],const std::size_t len)
,然后将值作为第二个参数传递。 (添加了{const
,因为您不想在函数中修改这些参数。编译器可以帮助您避免错误。) - 通过调用
std::strlen()
或类似方法来计算函数内部的大小。 - 接受已知大小:
void letter_frequency(const char le[400])
- 使用模板来推断大小,然后您的
sizeof
语句将起作用:
template<std::size_t N>
void letter_count( const char (&le)[N] )