Search code examples
c++cin

Can cin be connected to a string variable?


For example, if I type 'a', how do I print out the value of the variable a, i.e. "0 1"

string a = "0 1"; string c = "1 1";
string b = "0 1"; string d = "1 1";

cin>>
cout <<  

Solution

  • You are asking about some kind of instrospection like some interpreted languages have, but C++ doesn't work that way.

    This is not the right way to think about a C++ program (or in any other compiled language), the identifiers in the source code really disappear once the program is compiled.

    In other words, there is no automatic relation between the character entered (e.g. "a") and the variable std::string a in the source code.

    You have to manually do this:

    #include<string>
    
    int main(){
    
        std::string a = "0 1"; 
        std::string b = "0 1";
        std::string c = "1 1";
        std::string d = "1 1";
        
        char x; std::cin >> x;
        switch(x){
          case 'a': std::cout << a << std::endl; break;
          case 'b': std::cout << b << std::endl; break;
          case 'c': std::cout << c << std::endl; break;
          case 'd': std::cout << d << std::endl; break;
          default: std::cout << "not such variable" << std::endl;
        }
    
    }