Sebastian A Baker
Sebastian A Baker

Reputation: 5

Initialize an array with both upper and lowercase letters C++

//Loop to initialize the array of structs; set count to zero

for(int i = 0; i < 26; i++)
{
    //This segment sets the uppercase letters
    letterList[i].letter = static_cast<char>(65 + i);
    letterList[i].count = 0;

    //This segment sets the lowercase letters
    letterList[i + 26].letter = static_cast<char>(97 + i);
    letterList[i + 26].count = 0;
}

//this doesnt seem to work!!!

The entire program, takes a text file, reads it and then prints out each letter used, the number of times it was used and the percentage of occurance...however, my output keeps coming out as:

Letter Count Percentage of Occurrence

¿ 0 0.00%

52 times....

ive searched all over and cant seem to get this...

Upvotes: 0

Views: 2815

Answers (2)

cppcoder
cppcoder

Reputation: 23135

for(int i=0, c='a'; i<26; i++)
{
        letterList[i] = c++;
}
for(int i=26,c='a'; i<52; i++)
{
        letterList[i] = toupper(c++);
}

Alternatively, you can replace the second for loop with this:

for(int i=26,c='A'; i<52; i++)
{
        letterList[i] = c++;
}

EDIT

Based on your requirement to have struct
Assuming your struct has a char member and each struct instance carry each letter, this is the code:

struct letterType
{
    char letter;
};

int main()
{
    struct letterType letterList[52];
    char c;
    for(int i=0, c='a'; i<26; i++)
    {
            letterList[i].letter = c++;
    }
    for(int i=26,c='a'; i<52; i++)
    {
            letterList[i].letter = toupper(c++);
    }
    for(int i=0; i<52; i++)
    {
            cout<< letterList[i].letter << endl;
    }
}

Upvotes: 0

999k
999k

Reputation: 6565

I dont see any problem for this codes ouput

    letterType letterList[52];
    for(int i = 0; i < 26; i++)
    {
        //This segment sets the uppercase letters
        letterList[i].letter = static_cast<char>('A' + i);
        letterList[i].count = 0;

        //This segment sets the lowercase letters
        letterList[i + 26].letter = static_cast<char>('a' + i);
        letterList[i + 26].count = 0;
    }
    for (int i = 0; i < 26 * 2; i++)
        cout<<letterList[i].letter<<" "<<letterList[i].count<<endl;

Upvotes: 1

Related Questions