【问题标题】:Why is the compiler saying my integer variable is not being used?为什么编译器说我的整数变量没有被使用?
【发布时间】:2020-04-06 02:02:11
【问题描述】:

我收到一条警告说我的 int 变量未使用,但我正在使用它来存储我正在读取的文本文件中的整数值。

警告信息

menu.cpp:48:6: warning: unused variable ‘Release_year’ [-Wunused-variable]
   int Release_year;

menu.cpp

void Menu::LoadMovies(string filename)
{
    ifstream file;
    string line;
    string myString;

    string Movie_title, Lead_actor_actress, Description;
    int Release_year;

    file.open(filename.c_str());

    if (!file)
    {
        cout << "Unable to open file" << endl;
        exit(1);
    }

    while (getline(file, line))
    {
        stringstream ss(line);
        getline(ss, Movie_title, ',');
        getline(ss, Lead_actor_actress, ',');
        getline(ss, Description, ',');
        //Edit
        cin >> Release_year;
        //getline(ss, myString, ',');       //reading in the integer as a string for purpose of getline
        //Release_year = stoi(myString);   //converting it to an integer

    }

    file.close();

}

我读入和转换变量的语法是否错误?我知道警告是什么意思,但什么可能导致此警告?

【问题讨论】:

    标签: c++ stream compiler-warnings


    【解决方案1】:

    您分配给Release_year,但您从未阅读过它。

    因此它没有被使用。

    你确实在努力创造它的价值,但是却放弃了它。

    做无意义的工作并且从不使用它通常是一个错误。所以编译器有一个警告说“警告,你有一个你从未使用过的变量”。

    【讨论】:

    • 就像我说的,我明白为什么编译器会有这个警告。它基本上是它所说的。我删除了循环中的最后两个语句,而是只放了 cin >> Release_year; .....谢谢你的回复我的朋友
    • 如果有帮助,我的理解是在代码的其他地方,您使用其他变量 Movie_titleLead_actor_actress 等来执行某种工作(写入文件、打印到控制台,或类似的东西),但 Release_year 你没有。
    • @xcyb 更改会抑制编译器检测错误的能力,但不能消除问题。不要将警告视为要摆脱的东西;相反,他们告诉您您的代码有错误。找出错误;你为什么要读取数据然后丢弃它?如果要抑制错误,请添加注释,然后键入 (void)Release_year;,每个编译器都将其视为“不,我想丢弃它”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-24
    • 1970-01-01
    • 1970-01-01
    • 2015-01-25
    • 1970-01-01
    • 2021-10-31
    相关资源
    最近更新 更多