Here is my code:
#include <cstdlib>
#include <iostream>
#include <cstring>
using namespace std;
int main(int argc, char *argv[])
{
int duze[26];
int male[26];
int n;
//cout<<int('a')<<endl<<int('A');
cin>>n;
char temp;
for (int i=0; i<27; i++)
male[i]=0;
for (int i=0; i<27; i++)
duze[i]=0;
while (n>=0)
{
cin.get(temp);
if (temp=='\n') { n--; continue;}
if (temp==' ') continue;
if (temp>='a' && temp<='z')
male[temp-'a']++;
else if (temp>='A' && temp<='Z')
duze[temp-'A']++;
}
for (int i=0; i<27; i++)
if (male[i]>0) cout<<char(i+'a')<<" "<<male[i]<<endl;
for (int i=0; i<27; i++)
if (duze[i]>0) cout<<char(i+'A')<<" "<<duze[i]<<endl;
//system("pause");
return 0;
}
The program counts letters in given n lines of text. The letters that dont exist are skipped.
When I run it in console it looks ok, but I know that there are EOF characters before characters…
How can I avoid it?
Array indexes run from
0toN-1, whereNis the number of elements: all of theforloops access 1 too many resulting in undefined behaviour. Change terminating conditions onforloops toi < 26.Another minor note, to simplify the initialization of
duzeandmaleyou declare them as:This set all elements to
0, meaning you can remove the twoforloops that currently do this.