The specific problem in your code is that you didn't declare the variable x
before use. (And your declaration was weird. To declare a variable, put the type followed by the name, like char* x
, optionally followed by an assignment to initialize it, char* x = "hello world"
. After the variable has been declared, the compiler will let you use it.
#include <iostream> // include the header containing cout and cin
#include <string> // include the header containing the string class
// using namespace std; // don't do this. Prefix standard library names with the std namespace instead
int main()
{
std::cout << "Input a Sentence: ";
std::string x; // declare a variable named x, so we can use it afterwards - and use the C++ string class, not char*
//std::cin >> x; // only reads a word into x. If we want a sentence, use getline instead:
std::getline(cin, x);
int letter_count[26] = {}; // automatically fills the array with zeros
// Counting the number of letters
for(std::string::iterator it = x.begin(); it != x.end(); ++it) { // might as well use iterators. That's what they're for. And then your code behaves better if the string actually contains a \0 character.
if(*it >= 'A' && *it <= 'Z'){ // never leave out the {}'s. It'll blow up on you later, when you modify the code
letter_count[*it - 'A']++;
}
else if (*it >= 'a' && *it <= 'z'){
letter_count[*it-'a']++;
}
else if (*it == '.'){
break;
}
}
// Show the result
for(int i=0; i < 26; i++)
if (letter_count[i] != 0)
std::cout << letter_count[i] << " "<< static_cast<char>(i+97) << std::endl; // prefer C++-style casts
}
}