使用数据库结构的简单程序中的未声明标识符错误

Roh*_*rma -3 c++ compiler-errors

我的编译器没有编译我编写的以下程序.它给出了我标记为"标识符未声明"的行的错误,即使我已经在我的Main()函数中声明了它.

该程序不完整,但它将接受有关活动的输入并输出它.

#include <iostream.h>
#include <conio.h>


void addToLog();
void viewLog();

void what()
{
    cout << "What would you like to do?" << endl
         << "1. View Today's Log" << endl
         << "2. Add to Today's Log" << endl
         << "__________________________" << endl << endl
         << "? -> ";

    int in;

    cin  >> in;

    if ( in == 1 )
    {
        viewLog();
    }

    if ( in == 2 )
    {
        addToLog();
    }

}

void main()
{
    clrscr();


    struct database
    {
        char act[20];
        int time;
    };

    database db[24];



    what();



    getch();
}

void addToLog()
{
    int i=0;
    while (db[i].time == 0) i++;

    cout    << endl
        << "_______________________________"
        << "Enter Activity Name: ";
    cin     >> db[i].act;                           // <-------------
    cout    << "Enter Amount of time: ";
    cin >> db[i].time;
    cout    << "_______________________________";

    what();

}

void viewLog()
{
    int i=0;
    cout    << "_______________________________";
    for (i = 0; i <= 24; i++)
    {
        cout    << "1. " << db[i].act << "   " << db[i].time << endl; // <-------
    }
    cout    << "_______________________________";

    what();
}
Run Code Online (Sandbox Code Playgroud)

Oli*_*rth 5

您已声明db为局部变量main(); 其他功能无法看到它.

至少有两种解决方案:

  1. 创建db一个全局(静态)变量 - 即将其声明/定义移出main(). 通常不建议这样做,因为过分依赖全局变量通常是不好的做法.
  2. 将指针传递给db需要它的函数.