c++ - 在 Eclipse IDE C++ 中未在此范围内声明的变量

标签 c++ eclipse

我正在使用 Eclipse C++ 来学习编程,但由于未在此范围内声明变量,我无法让程序完全编译。我承认我很糟糕,而且是编程新手,但是有人可以提供任何帮助吗?例如,

/*
datatypes.cpp
Aug 25, 2014
gauvey42684
*/
#include <iostream>
using namespace std;
int main()
{
    char letter = 'a';
    short age = 10;
    int count = 575;
    long numStars = 985467528;
    float pi = 3.14;
    double price = 89.65
    string season = "summer";

    cout<<"letter"<<letter<<endl;
    cout<<"age"<<age<<endl;
    cout<<"count"<<count<<endl;
    cout<<"Number of Stars in the Sky"<<numStars<<endl;
    cout<<"pi: "<<pi<<endl;
    cout<<"price: $"<<price<<endl;
    cout<<season<<season<<endl;
return 0;
}

在这行代码中,最后一个 cout 处的变量 season 没有在此范围内声明。

再举个例子,

/*
C++lesson.cpp
Aug 22, 2014
gauvey42684
*/
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
// variables
    double mpg, distance, gallons, pricepergallon, totalcost

        //output using insertiuon operator
        cout<<"Enter mpg"<<endl;

        //input using extraction operator
        cin>>mpg;

        cout<<"Enter Distance in miles"<<endl;
        cin>>distance;
        cout<<"Enter Price for one gallon of gas"<<endl;
        cin>>pricepergallon;
        //calculate gallons needed
        gallons=distance/mpg;
        //calculate total cost
        totalcost=gallons * pricepergallon;
        cout<<"Total Trip Cost: $"<<fixed<<setprecision(2)<<totalcost<<endl;
return 0;
}

在此程序中,totalcost 也不能​​在此范围内声明。有什么建议吗?

最佳答案

语法错误往往会使编译器感到困惑。

当我编译上面的代码时,我得到的第一条消息是关于缺少分号的。具体来说,编译器 (g++ 4.8.2) 提示:

c.cpp: In function ‘int main()’:
c.cpp:16:5: error: expected ‘,’ or ‘;’ before ‘string’
     string season = "summer";
     ^
c.cpp:24:11: error: ‘season’ was not declared in this scope
     cout<<season<<season<<endl;
           ^

第一个错误是语法错误,由缺少 ; 引起。编译器变得如此困惑(更准确地说,它失去了其内部数据结构为源文件建模的能力),以至于它不知道应该使用逗号还是分号。它甚至无法识别这条线

string season = "summer";

作为变量声明——这就是为什么它后来将其报告为未声明的标识符。

您的第二个示例中发生了非常相似的事情。你忘记了分号

double mpg, distance, gallons, pricepergallon, totalcost

这里有两个教训:

首先,在发布有关编译失败的问题时,请始终将编译器生成的确切错误消息复制并粘贴到问题中。不要总结消息所说的内容,向我们展示。在这种情况下,您遗漏了重要信息。

其次,如果您的编译器报告语法错误,请直接转到消息中报告的行。研究那行代码和它之前的几行代码。查找缺少的标点符号、拼写错误等。语法错误的错误消息可能提供信息,也可能不提供信息——但它应该告诉您编译器检测到错误的确切位置。 (对编译器如何解析源代码有一些了解会有所帮助,但这并不是真正必要的。)如果在第一个语法错误之后还有其他错误消息,不要太担心理解它们;先修正语法再重新编译。

(根据编译器的不同,语法错误消息可能包含也可能不包含“语法”一词。通常它会告诉您编译器希望在特定点看到什么标记或标记。其他错误是 语义 错误,如未声明的标识符、应用具有错误操作数类型的运算符等)

关于c++ - 在 Eclipse IDE C++ 中未在此范围内声明的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25510783/

相关文章:

c++ - 两次调用 cout 是否比一次调用效率低?

c++ - KissFFT 中 FFTW 的 fftw_plan_dft_r2c_1d() 的等效函数是什么?

c++ - 为什么我在使用 Boost UUID 时会收到来自 Valgrind 的未初始化值警告?

java - 使用 GitHub Java API 检索有关登录用户的信息?

c++ - C/C++ 中的 const 数组和静态 const 数组有什么区别

c++ - 在函数退出前调用函数

java - Eclipse 如何运行 map reduce 作业?

java - 需要从 eclipse 插件的本地调试更改为 vm 中的远程调试

java - 将项目从 eclipse 导入到 intelliJ 时

eclipse - 无法计算构建计划:artifact org. apache.maven.plugins :maven-resources-plugin:pom:2. 4.3在本地存储库中不可用