C++ 我不知道如何引用循环外的变量(C+;+;)

C++ 我不知道如何引用循环外的变量(C+;+;),c++,C++,基本上我的问题是我在循环外创建了一个变量(字符串),我想在循环内使用它。下面是一个示例代码,试图更好地解释: int myage = 0; // set by user int currentyear = 2015; cout << "How old are you?" << endl; cin >> myage; for(int i=0; i>98; i++) { myage=myage+1; currentyear=currentyear

基本上我的问题是我在循环外创建了一个变量(字符串),我想在循环内使用它。下面是一个示例代码,试图更好地解释:

int myage = 0; // set by user
int currentyear = 2015;

cout << "How old are you?" << endl;
cin >> myage;

for(int i=0; i>98; i++) {
  myage=myage+1;
  currentyear=currentyear+1;

  cout << "In " << currentyear << " you will be " << myage << " years old." << endl;
}
int myage=0;//由用户设置
int当前年份=2015年;
cout-myage;
对于(int i=0;i>98;i++){
我的年龄=我的年龄+1;
当前年份=当前年份+1;

cout循环从不执行

for(int i=0; i>98; i++){

因为如果你问的是我认为你在问的问题,那么
i>98
绝对是
false

。for循环几乎更像是一种方便的语法,让你可以指定初始条件、中断条件和执行每一次迭代的命令。据我所知,你可以使用尽可能多或尽可能少的这些条件比如,你想要什么

#include <iostream>
int main(){
    int myage = 0;
    for(; myage<10; myage++)
        std::cout << myage << std::endl;
}
#包括
int main(){
int myage=0;

对于(;myage,既然已经回答了这个问题,您可以使用+=运算符来改进和缩短代码,如下所示:
myage+=1;

或者这个:
myage++;


myage=myage+1;

相反,理解作用域很重要。循环和函数创建一个作用域,它们总是可以在更高的作用域访问内容;但是,不能从更小的作用域访问内容。对象在其作用域的整个期间都存在,并且该作用域内的任何内容都可以访问它们

// Global scope:
int g = 0; // everything in this file can access this variable

class SomeClass
{
    // Class scope
    int c = 0;
    void ClassFunction()
    {
        // ClassFunction scope
        // Here we can access anything at global scope as well as anything within this class's scope:
        int f = 0;

        std::cout << g << std::endl; // fine, can access global scope
        std::cout << c << std::endl; // fine, can access class scope
        std::cout << f << std::endl; // fine, can access local scope
    }
    // Outside of ClassFunction, we can no longer access the variable f
};

void NonClassFunction()
{
    // NonClassFunction scope
    // We can access the global scope, but not class scope
    std::cout << g << std::endl;

    int n1 = 0;
    for (...)
    {
        // New scope
        // Here we can still access g and n1
        n1 = g;
        int x = 0;
    }
    // We can no longer access x, as the scope of x no longer exists

    if (...)
    {
        // New scope
        int x = 0; // fine, x has not been declared at this scope
        {
            // New scope
            x = 1;
            g = 1;
            n1 = 1;
            int n2 = 0;
        }
        // n2 no longer exists
        int n2 = 3; // fine, we are creating a new variable called n2
    }
}
//全局范围:
int g=0;//此文件中的所有内容都可以访问此变量
上课
{
//类范围
int c=0;
void类函数()
{
//类函数作用域
//在这里,我们可以访问全局范围内的任何内容以及此类范围内的任何内容:
int f=0;

如果你不能使用它们,你会得到一个编译器错误。我不能在循环中使用myage(你是正确的)您已经更改了您的问题,现在您的代码在编译和运行时按照所述工作。您是否收到错误消息?是什么?是的,它说变量myage可能未初始化您的示例代码不会为我重现错误。感谢您让我知道,但我很快编写了此示例,以更好地解释我的问题。令人沮丧的是,OP改变了这个问题,这使得这个答案变得过时。难道我不应该改变它吗?是的,确实令人沮丧:)谢谢你的帮助。非常有用,因为我正在学习代码。谢谢你分享这个!