while 循环中变量的作用域(以 C++ 为单位)

Scope of a variable in while loop (in C++)

本文关键字:C++ 为单位 作用域 循环 变量 while      更新时间:2023-10-16

我正在用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;