0

此代码应该在文件中搜索每个客户端的 iterNo,然后显示该信息。我的问题是,无论我搜索什么数字,它总是显示文件中的第一项。任何帮助将不胜感激。现在真的很绝望......提前感谢您的回复。

void View()
{       
    char ans; //answer to store 'y' or 'n'
    Intervention inte;
    int interNo;

    ifstream InfoFile("info.dat", ios::in |ios::binary|ios::app);
    if (!InfoFile)
    {
        cout <<"Error - random files could not be opened.";
    }
    else
    {
        while (true)
        {
            cout << "\nEnter client's interNo number to display ";

            cin >> interNo;

            inte.getClient();
            inte.getAddress();
            inte.getTelNo();
            inte.getTime();
            inte.getDate();
            inte.getAnimal();

            //InfoFile.seekg(sizeof(Intervention)*(interNo - 1));
            InfoFile.read(reinterpret_cast<char *> (&inte), sizeof(Intervention));
            //if not eof show data
            if (!InfoFile.eof())
            {
                //Display the processed
                // info for the employee
                inte.display();
            }
            cout << "Enter another employee's information to display ? [y / n] ";
            fflush(stdin);
            ans = ' ';
            while (ans != 'y' && ans != 'Y' &&
                ans != 'n' && ans != 'N')
            {
                ans = _getch();
            } cout << endl;
            if (ans == 'n' || ans == 'N')
            {
                exit(1);
            }

        }//end while

    }//end else

}//end function view
//**********************************************
4

1 回答 1

0

Well the code does what it should do. You don't check anywhere if the found Intervention is the one you look for, nor you don't move the file read pointer.

If you store IDs inside the file

You only read the Intervention once too:

InfoFile.read(reinterpret_cast<char *> (&inte), sizeof(Intervention));

Maybe you meant to check if the Intervention has the ID you inputted?

while(inte.getID()!=interNo && InfoFile)
  InfoFile.read(reinterpret_cast<char *> (&inte), sizeof(Intervention));

If you don't

You need to uncomment the line of code that you must've commented out earlier:

InfoFile.seekg(sizeof(Intervention)*(interNo - 1));

This line actually should position the read pointer to a place in the file, where the given Intervention is written. Check out the C++ reference page for more detail on the read pointer.

于 2013-11-11T03:48:06.697 回答