cin可以连接到字符串变量吗?

问题描述 投票:0回答:2

比如我输入

'a'
,如何打印出变量
a
的值,即
"0 1"

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

cin>>
cout <<  
c++ cin
2个回答
3
投票

您确定不是在寻找地图吗?

#include <iostream>
#include <string>
#include <map>

using namespace std;

int main(void) {
    map<string, string> m;

    m.insert(pair<string, string>("a", "0 1"));
    m.insert(pair<string, string>("b", "0 1"));
    m.insert(pair<string, string>("c", "1 1"));
    m.insert(pair<string, string>("d", "1 1"));

    // Or just:
    // map<string, string> m = {
    //   {"a", "0 1"}, {"b", "0 1"},
    //   {"c", "1 1"}, {"d", "1 1"}
    // };

    string user_choice = "a";

    cout << "Which letter?" << endl;
    cin >> user_choice;
    cout << "For " << user_choice << ": " 
         << m.at(user_choice) << endl;
}

A

std::map
正如其所说。它将一种类型的值映射到另一种类型,这听起来像是您想要做的,并且它不使用变量名,正如其他人指出的那样,变量名在编译后被丢弃。

使用标准模板库中提供的功能可以对地图执行各种有用的操作。


1
投票

你问的是某种像某些解释语言那样的内省,但 C++ 不是这样工作的。

这不是思考 C++ 程序(或任何其他编译语言)的正确方式,一旦程序被编译,源代码中的标识符就会真正消失。

换句话说,输入的字符(例如

"a"
)与源代码中的变量
std::string a
之间没有自动关系。

您必须手动执行此操作:

#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;
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.