#include <iostream>
#include <fstream>
#include <iomanip>
usingnamespace std;
int main()
{
int total[26] = { 0 };
ifstream infile("cipher.txt");
if (!infile)
{
cout << "Error opening cipher file" << endl;
return 0;
}
char c;
while (infile.get(c)) // read characters one at a time
{
if (isalpha(c)) // check it is a-z or A-Z
{
int index = c - 'A'; // index in range 0 to 25;
total[index]++; // increment corresponding total
}
}
for (int i = 0; i<26; i++) // Print the results
{
cout << " " << char(i + 'A') << " occurs "
<< setw(5) << total[i] << " times" << endl;
}
system("pause");
return 0;
}
index isn't going to be in the range you think it'll be in. It might be arduous, but your best bet is a huge if/else block that assigns 0 to 'a' and 'A', 1 to 'b' and 'B', and so on. Your program is going to crash often because index will quite often have values outside the range 0-25.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cctype> // std::isalpha(), std::toupper()
int main()
{
constchar alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ;
int total[26] = { 0 };
std::ifstream infile( "cipher.txt" );
if (!infile) { /* ... */ }
char c;
while( infile.get(c) ) // read characters one at a time
{
if( std::isalpha(c) ) // check it is a-z or A-Z
{
c = std::toupper(c) ; // convert lower case to upper case
// get the index of the upper case letter
int index = 0 ;
while( alphabet[index] != c ) ++index ;
// index in range 0 to 25;
++ total[index] ; // increment corresponding total
}
}
for( int i = 0; i<26; ++i ) // Print the results
{
std::cout << " " << alphabet[i] << " occurs "
<< std::setw(5) << total[i] << " times\n" ;
}
}
First off it will help if you open the file in binary mode, otherwise any control characters might get all screwy. Second, if you're looking at a cipher that has mixed upper and lower case letters then chances are that those letters are completely different, in other words 'a' and 'A' are not the same letter being encoded. Thirdly why aren't you using std::count from the Algorithm header?: http://www.cplusplus.com/reference/algorithm/count/?kw=count