-3

我的编译器不会编译我编写的以下程序。它在我标记的行中给出了一个错误,指出“未声明标识符”,即使我已经在我的 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();
}
4

1 回答 1

5

You have declared db as a local variable in main(); it cannot be seen by other functions.

There are at least two solutions:

  1. Make db a global (static) variable - i.e. move its declaration/definition out of main(). This is generally not recommended, as it's usually poor practice to rely on global variables too much.
  2. Pass a pointer to db into functions that need it.
于 2012-04-29T13:29:36.673 回答