Johnapples
Johnapples

Reputation: 35

Retrieving a variable from an array

Ok so the problem I am having is that I have an array that contains 27 characters and I need to write a function to display a specific character 0 - 25 based on a user input.

The array is a constant string:

const string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

And the idea is that a user enters a value between 1 and 25 (int value) which then displays the cosponsoring letter in the array. I doing this by using:

cout << ALPHABET[value];

My questions are is this an appropreate way to create an array and am I able to retrieve a value from an array this way.

const string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

int main()
{
    int value; //Variable defining user entered value
    cout << "Please enter a number between 0-25." << endl;
    cin >> value;
    if (value > 25) //If statement to display "-1" if number entered is past "Z"
        cout << "-1" << endl;
    else
        cout << ALPHABET[value];

    return 0;
}

Upvotes: 2

Views: 282

Answers (2)

Andreas DM
Andreas DM

Reputation: 11028

My questions are is this an appropreate way to create an array and am I able to retrieve a value from an array this way.

Although it works to use a string:

int main()
{
    const string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    int num = -1;
    while (num < 0 || num > 25) {
        cout << "Enter number (0 - 25): ";
        cin >> num;
    }

    cout << ALPHABET[num] << '\n';
}

I like to use a std::vector for containing a sequence of elements:

vector<char> ALPHABET(26);
iota(begin(ALPHABET), end(ALPHABET), 'A');

Upvotes: 1

Cahelle
Cahelle

Reputation: 11

Maybe this is what you want to do. Which includes a right way to create an array.

#include <iostream>

char ALPHABET[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '\0' }; 
//the \0 means the end of the array of characters a.k.a. a string

int main()
{
    int value; //Variable defining user entered value
    std::cout << "Please enter a number between 0-25." << std::endl;
    std::cin >> value;

    if (value > 25 || value < 0) //If statement to display "-1" if number entered is past "Z"
        std::cout << "-1" << std::endl;
    else
        std::cout << ALPHABET[value];

return 0;
}

(There are more ways to create an array) Like "char ALPHABET[26] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '\0' };

The 26 means there can NOT be more than 26 characters in this array.

If you're confused about me not using "using namespace std;" and instead "std::", if you have two namespaces with "cout" or "endl" in them the program won't know which one you want to use.

So if you want to make sure it is from the right namespace, use the name of the namespace and two colons.

Upvotes: 0

Related Questions