在循环内更改变量名称 [英] Changing variable name inside a loop

查看:233
本文介绍了在循环内更改变量名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个循环,该循环将创建一个新变量,但也会自动更改该变量的名称,例如自动增加值。不知道是否可以这样做,因为您不能拥有动态变量?

I'm trying to create a loop that will will create a new variable but also change the name of the variable, such as increasing in value, automatically. Not sure if this is possible because you cant have dynamic variables?

if (cin.get() == '\n')
{
    m ++; // Add an integer to m
    string (1 + m); //Trying to name the string the value of m + 1, i.e 3
    cin.ignore():
    getline(cin, (1 + m))
    myfile << (1 + m) << endl;
}

这是我当前的代码,虽然有很多错误,但希望可读性足以对我正在尝试做的事情的理解。

That is my current code which is full of errors but hopefully readable enough to gain an understanding of what I'm trying to do.

标题错误,不知道该怎么称呼。

Bad title, don't know what else to call it.

推荐答案

如果尝试重命名变量,则会误解C ++。

You're misunderstanding C++ if you try to "rename a variable".

C ++是一种编译语言,其中变量的名称仅存在于源代码中代码作为处理它们的一种方式,但不在编译程序中。

C++ is a compiled language in which the names of the variables only exist in your source code as a means of handling them, but not in the compiled program.

因此,您也无法在运行时创建具有特定名称的变量-那时变量名根本就不存在。

You hence can't also create a variable with a specific name at runtime -- variable names simply don't exist then.

您可能想要某种将值映射到键的容器,想一想字典,在其中您可以说对于此整数值 12 ,则存储字符串 monkey 左右。看看 std :: map

You probably want some kind of container that maps values to keys, think of a dictionary, where you can say "for this integer value 12, I store the string monkey" or so. Have a look at std::map.

现在,您现在真的没有多大意义;并尝试做并非真正以有序方式学习C ++的人做的事情。我真的建议获得一本C ++书籍或教程,并从此开始。事实证明,这可以让您安全很多! 此处列出了推荐的C ++书籍和资源。

Now, you're really not making much sense right now; and try to do things that aren't really the way C++ works for anyone who learned it in a ordered manner. I'd really recommend getting a C++ book or tutorial and start with that. It's going to turn out to safe you a lot of time! Here's a list of recommended C++ books and ressources.

这篇关于在循环内更改变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆