Указатель файла читает только первую запись - PullRequest
0 голосов
/ 11 декабря 2018

Добрый день всем.Моя программа о компьютерном магазине (ноутбуке).Таким образом, люди могут купить ноутбук через эту программу, и «PCPurchase» - это функция, которая будет обрабатывать транзакции клиента.

Я использую указатель файла и структуру для сохранения информации обо всех ноутбуках.И, конечно, структура хранит более 1 типа ноутбуков, потому что, очевидно, это магазин ноутбуков.

Я столкнулся с проблемой, когда пользователь может купить (ввести имя) только первую запись (первый ноутбук) в структуре.Здесь: cout << "Enter the laptop company and name you want to buy: " << endl;

Если клиент введет имя 2-го ноутбука, 3-го и т. Д., Он перейдет к строке cout << endl << "\tNot available!" << endl; cout << "\tPress A to try again or B to return to main menu" << endl; Это указывает на то, что имя ноутбука отсутствует в базе данных, которая на самом деле.

Могу я узнать, в чем здесь проблема?

int PCPurchase()
{
    struct customer cust;
    system("color 0A");
    char laptop[100];
    double total_bill;
    const double TAX=0.06;

    system("cls");
    cout << setfill ('-') << setw (55) << "-" << endl;
    cout << "\t\tCustomer Dashboard" << endl;
    cout << setfill ('-') << setw (55) << "-" << endl;

    fptr=fopen("laptop.txt","ab+");
    cout << "Available laptops: " << endl;
    rewind(fptr);
    while(fread(&PC,sizeof(PC),1,fptr)==1)
    {
        cout << endl << "Laptop company and name: ";
        cout << PC.laptopcompany << endl;
        cout << "RAM: ";
        cout << PC.RAM << endl;
        cout << "Processor: ";
        cout << PC.Processor << endl;
        cout << "Price: RM";
        cout << PC.price << endl;
    }
    cout << "\nPress any key to continue purchase" << endl;
    getch();
    fflush(stdin);

    getInfo(cust); //get information of customer

    cout << "Enter the laptop company and name you want to buy: " << endl;
    cout << "(Type 'RETURN' if you do not want to purchase)" << endl << endl;
    gets(laptop);
    rewind(fptr);
    while(fread(&PC,sizeof(PC),1,fptr)==1)
    {  
        if(strcmpi(PC.laptopcompany,laptop)==0)
        {
            cout << setfill ('-') << setw (55) << "-" << endl;
            cout << "\tYou have selected" << endl;
            cout << setfill ('-') << setw (55) << "-" << endl;
            cout << "Laptop company and name: ";
            cout << PC.laptopcompany << endl;
            cout << "RAM: ";
            cout << PC.RAM << endl;
            cout << "Processor: ";
            cout << PC.Processor << endl;
            cout << "Price: ";
            cout << PC.price << endl;

            total_bill=PC.price+(PC.price*TAX);

            cout << setfill ('-') << setw (55) << "-" << endl;
            cout << fixed << showpoint << setprecision (2);
            cout << "Name: "<< cust.name << endl; // struct output
            cout << "Email: "<< cust.email << endl;
            cout << "Phone Number: " << cust.number << endl;
            cout << "Your total bill (including 6% tax): RM" << total_bill << endl;
            cout << setfill ('-') << setw (55) << "-" << endl;

            cout << endl << "\tPress 1 to return to main screen!";
            cout << endl << "\tPress 2 to quit the program!";

            char afterpurchase;
            afterpurchase=getche();

            if (afterpurchase=='1')
            {
                fclose(fptr);
                main();
            }
            else
                exit_system();
        }
        else if(strcmpi("RETURN",laptop)==0)
            main();
        else
        {
            cout << endl << "\tNot available!" << endl;
            cout << "\tPress A to try again or B to return to main menu" << endl;
            char choice1;
            choice1=getche();
            choice1=toupper(choice1); // Transform to uppercase

            switch (choice1)
            {
                case 'A': fclose(fptr);
                          PCPurchase();
                          break;

                default : fclose(fptr);
                          main();
                          break;
            }
        }
    }
}

1 Ответ

0 голосов
/ 12 декабря 2018

Это из-за утверждения else.Если вы хотите купить ноутбук со второй записи данных и так далее, он будет сравниваться с первой записью и не вернет истину.Таким образом, он перейдет к оператору else и не будет повторять цикл while.Просто измените оператор else, чтобы цикл работал.

...