【发布时间】:2015-12-16 01:32:10
【问题描述】:
任务:编写一个程序,读取一行文本并输出每个字母出现的次数。
#include <iostream>
#include <string>
#include <cstring>
#define N 100
using namespace std;
int main()
{
char alphabet[27] = "abcdefghijklmnopqrstuvwxyz";
int alphacount[26];
char lot[N], *p1;
int txtlen, *p2;
cout << " Enter a line of text: " << endl;
cin.getline(lot, 99);
txtlen = strlen(lot);
p1 = lot;
p2 = &txtlen;
for (int x = 0; x < *p2; x++)
{
for (int y = 0; y < 26; y++)
{
if (*p1 == alphabet[y])
{
alphacount[y]++;
p1++;
}
}
}
cout <<;
}
需要什么条件,用什么变量来输出出现的字母?例如:
> enter a line of text : mervlala
输出:
a - 2,
e - 1,
l - 2,
m - 1,
r - 1,
v - 1
【问题讨论】:
-
你需要遍历
alphacount并打印非空值。 -
离题:
p2是不必要的。切勿在不必要的地方使用指针。 -
您的计算循环不正确(尽管一旦您的输出正常工作,调试起来会更容易)
标签: c++