while 循环中变量的作用域(以 C++ 为单位)
Scope of a variable in while loop (in C++)
我正在用c ++编写代码,其中必须完成以下操作 - 创建用户想要的变量数。这是代码
#include <iostream>
using namespace std;
int main(){
cout<<"how many variables do you want to enter"<<endl;
int numVar;
cin>>numVar;
int i=0;
while(i<numVar){
i++;
static int termi;
// creates 'numVar' number of terms
cout<<"enter term"<<i<<endl;
cin>>termi;
//the user gives values of each term
}
// I want to cout all the terms here and do some calculations
return 0;
如何在循环外使用创建的变量?我已经签到-learncpp.com 但找不到满意的答案。
在main
中声明一个变量作为static
是没有用的,只是不要这样做。此外,您不能按照您尝试的方式在运行时"创建"变量。您希望改用std::vector
并在循环之前声明它。您可以使用这样的东西来读取值:
size_t num;
std::cin >> num;
std::vector<int> terms(num);
for (auto& e: terms) std::cin >> e;
相关文章:
- 以天C++为单位的两个时间戳之间的差异
- 如何以毫秒为单位获取开始时间和 now() 之间的毫秒差异(以 C++为单位?
- 从原始字节解码协议缓冲区(以 C++为单位)
- 如何在 c++ 中确定一条指令(以字节为单位)在哪里结束,另一条指令从哪里开始?
- 编写以 C++ 为单位返回值的函数
- 以C++为单位进行运行长度编码
- 如何找到两个日期之间的时间差异(以秒和纳秒为单位)?
- arr[n] 是否以 C++ 为单位打印数组的长度?
- 字符串数组上的 sizeof 运算符以 C++ 为单位给出不同的输出
- 以 C++ 为单位具有输出限制的排列
- 以 GDB 为单位指定浮点精度
- 整数数据如何以位为单位存储在内存中?不是右对齐吗?
- 如何在没有硬编码的情况下以C++为单位获取类数组的长度?
- 指针引用的生存期(以 C++为单位)
- 以字符为单位设置控制台大小
- 获取嵌套 stl 容器的大小(以字节为单位)
- 有没有一种 STL 方法可以找到字符串的所有排列,给出一个以 C++ 为单位的大小?
- 二进制数组中最大连续 1 的起始和结束索引,以 C++ 为单位
- 正向声明的枚举,默认值以.h为单位
- 常量"C"占用的空间(以字节为单位)