-4

I want to pick from keyboard which array i want to display (i know my code doesn't work i just want to show my problem)

 int main(){
            char *a = new char[5];
            char *b = new char[5];
            char name;

            cin >> a;
            cin >> b;
            cin >> name;

            cout << name; 
}
Rooster
  • 13
  • 3

2 Answers2

1

The variable names you use in your code have no meaning once your program is running. You cannot dynamically replace name with either a or b, if thats what you wanted to do.

Making the example simpler (c-style arrays are definitely not for beginners, look at std::vector instead), you can do this:

#include <iostream>
int main() {
    int a = 42;
    int b = 102;
    std::cout << "select a or b: ";
    char select;
    std::cin >> select;
    if (select == 'a') std::cout << a;
    else if (select == 'b') std::cout << b;
    else std::cout << "wrong input \n";
}
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
0

Most of the time, if you want to have a number of objects (say, more than 2 or 3) of the same type, you should consider using an array or vector.

So instead of

char *a = ...;
char *b = ...;
char *c = ...;

Use

char *values[] = { ... };

Now you can access a value by using an index, i.e. an integer value. For a character a-z, this can easily be done by subtracting the value 'a' ('a'-'a' is 0, 'b'-'a' is 1, etc).

const char *values[] = { "this is a", "this is b" };

char name;
std::cin >> name;
int index = name - 'a';

// TODO: Make sure the index is in range!
const char *value = values[index];
std::cout << value;
Kevin
  • 6,993
  • 1
  • 15
  • 24