如何在C ++中使用变量?

时间:2016-09-23 18:54:37

标签: c++

我想让num显示nr1,nr2和nr3的值。有什么想法吗? THX !!

#include <iostream>
#include "../std_lib_facilities.h"

using namespace std;

int main() {
    int count=3;
    string num;
    double nr1=111;
    double nr2=222;
    double nr3=333;

    for(int i=1;i<=count;i++) {
        ostringstream number {};
        number << "nr" << i;
        num=number.str();
        cout << "Num: " << num << endl;
    }
}

2 个答案:

答案 0 :(得分:2)

如果您的意图是通过运行时字符串引用变量,则无法执行此操作。 (例如在 php 中你可以用$$variable来做,在 C ++ 中没有那种功能。)

最相似的方法是使用预处理器,但我强烈建议你避免使用它,因为通常这种解决方案非常“脏”

最简单和最优的解决方案是使用数组,然后使用索引访问变量。

一个小例子:

int main(int argc, char *argv[]) {
  std::array<double, 3> nrs = {111, 222, 333};
  for (int i = 0; i < nrs.size(); ++i) {
    std::cout << "Num" << i + 1 << ": " << nrs[i] << '\n';
  }

  return 0;
}

这种方法有很多变体,例如:你可以使用std::vector是在编译时未定义的变量数。

我认为这将解决您的问题。

无论如何只是为了完整性,还有另一种方法来“地址”一个带名字的变量。原理是相同的,但您可以使用字符串名称而不是使用数字索引。

只需使用maphash即可实现。

int main(int argc, char *argv[]) {
  std::map<std::string, double> nrs = {std::make_pair("nr1", 111),
                                       std::make_pair("nr2", 222),
                                       std::make_pair("nr3", 333)};

  for (int i = 0; i < nrs.size(); ++i) {
    std::string num = "nr" + std::to_string(i + 1);
    std::cout << num << ": " << nrs.at(num) << '\n';
  }

  return 0;
}

因此,使用方法at,您可以访问与该名称关联的值。

注意:如果找不到变量名,则会尝试访问异常。

答案 1 :(得分:1)

执行此操作的典型方法是使用std::map,如下所示:

int main()
{
    std::map<std::string, double> nums;

    nums["nr1"] = 111;
    nums["nr2"] = 222;
    nums["nr3"] = 333;

    for(int i = 1; i <= 3; i++)
    {
        std::ostringstream number;
        number << "nr" << i;
        std::string num = number.str();
        std::cout << "Num: " << nums[num] << '\n';
    }
}