制作一个程序来计算字母表中每个字母的出现次数

Making a program that counts the amount of occurrences for each letter in the alphabet issues

本文关键字:计算 一个 程序 字母表      更新时间:2023-10-16
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
string text;
int i;
char x;
int n = 0;
int main(int argc, const char * argv[])
{
    cout << "Enter some text: " << endl;
    getline(cin, text);
    for (x = 'a'; x <= 'z'; x++)
    {
        for (i = 0; i<= text.length(); i++)
        {
            if (text[i] == x)
            {
                n++;
                cout << x << ": " << n << endl;
            }
        }
    }
}

所以我希望它打印出字符串中出现的每个字母的出现次数,但相反,我得到这个:

输入:你好

输出:

e: 1
h: 2
l: 3
l: 4
o: 5

理解为什么每次找到字母时它都会计数,但是我如何让它显示每个字母实际出现的次数。例如,这就是我想说的:

e: 1
h: 1
l: 2
o: 1

在每个循环(x(的开头,你应该将n重置为0。

您还应该移动语句

cout << x << ": " << n << endl;

从第二个循环到第一个循环的结束