1

So here's my code at the moment:

#include <iostream>
using namespace std;

int main() {
    string x = "_one";
    int sound_one = 7;
    int sound_two = 8; 
    cout << ("sound") + x;
}

However when I run the code, it outputs 'sound_one' instead of '7'. How do I get it to output the variable sound_one instead of just 'sound_one'? Also, I need it so I can change x to different things (eg '_two') so it will then output sound_two instead. Any help would be greatly appreciated.

Jack
  • 451
  • 1
  • 5
  • 10
  • 3
    You cannot do that in C++. C++ does not work this way. What is the real problem you're trying to solve? No, not the one about using variables this way, but the real problem to which you believe the solution involves using variables this way so that's what you're asking about. If you explain what the real problem is, I'm sure there's a C++ solution for that. But this isn't it. – Sam Varshavchik Jan 04 '21 at 14:53
  • https://stackoverflow.com/questions/7143120/convert-string-to-variable-name-or-variable-type may be a hashmap could solve your problem of keeping integer values against string keys, if it is what you are after – choppe Jan 04 '21 at 14:55
  • Does this answer your question? [execute C++ from String variable](https://stackoverflow.com/questions/15841511/execute-c-from-string-variable) – Aykhan Hagverdili Jan 04 '21 at 14:55
  • C++ doesn't knows how to count alphabetically: One, Two, Three, etc. – Rohan Bari Jan 04 '21 at 14:57

3 Answers3

3

C++ is not a reflective language in the sense that you can acquire a variable name at runtime (variable names are normally compiled out of the program). You can use std::map though to achieve your immediate aim:

#include <iostream>
#include <string>
#include <map>
 
int main() {
    using std::literals::string_literals::operator""s;

    std::string x = "_one";
    std::map<std::string, int> data;
    data["sound_one"] = 7;
    data["sound_two"] = 8;
    std::cout << data["sound"s + x];
}

Note the notation "sound"s: the suffixed s denotes a std::string user defined literal.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

You can't a variable from a string in this way. A work around is to use if/switch statements until the variable name is matched and then print it:

if(x == "_one") {
   cout << sound_one;
}
else if(x == "_two") {
   cout << sound_two;
}
else {
   cout << "no match";
}
Chris Wilhelm
  • 141
  • 1
  • 6
1

You can't do that in C++. You can use a map as shown in another answer, but I feel like what you really need is an array:

#include <format>
#include <iostream>

int main()
{
    int data[] { 7, 8 };
    std::cout << std::format("data[{}] = {}\n", 0, data[0]);
}

Arrays are usually better for such simple ordered sequences.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93