【问题标题】:Scope of a variable in while loop (in C++)while 循环中变量的范围(在 C++ 中)
【发布时间】:2017-10-20 10:13:44
【问题描述】:

我正在用 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() 中和循环外的变量,请在main() 内但在循环外定义它们。声明 static 不会使其名称在其封闭范围之外可访问。

标签: c++ variables while-loop scope


【解决方案1】:

main 中的变量声明为static 是毫无用处的,请不要这样做。此外,您不能以您尝试的方式在运行时“创建”变量。您想改用 std::vector 并在循环之前声明它。你可以使用这样的东西来读取值:

size_t num;
std::cin >> num;
std::vector<int> terms(num);
for (auto& e: terms) std::cin >> e;

【讨论】:

    猜你喜欢
    • 2013-02-25
    • 2023-03-31
    • 2016-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-12
    • 2023-03-08
    • 2011-12-06
    相关资源
    最近更新 更多