用映射来解决这个问题是比较方便的,因为映射是键和附加数组的二元组,存好之后就可以直接输出来。以前用C语言数组写过这个题,就没有这么方便了。
#include<iostream>
#include<map>
#include<cctype>
using namespace std;
int main()
{
map<char, int >s; //s是一个映射
char c;
do
{
cin >> c;
if (isalpha(c)) //是字母
{
c = tolower(c); //如果是字母全部变成小写形式需要<cctype>头文件
s[c]++;
}
} while (c != '.');
for (map<char, int>::iterator iter = s.begin(); iter != s.end(); ++iter) //用迭代器遍历
cout << iter->first << " " << iter->second << " "; //输出迭代器的第一个参数char类型,第二个参数int类型
cout << endl;
return 0;
}