拍卖项目:cin出现C++错误

Auction project: C++ error with cin

本文关键字:C++ 错误 出现 cin 项目 拍卖      更新时间:2023-10-16

我正在做一个项目,该项目假设复制一个拍卖。我想问一下第一个投标人的名字,如果投标人的名字是黑色的,就会给出一条错误消息,说BidderID是空白的。

问题

在询问"Bidder1 ID"后,代码会自动跳过cin,并直接返回错误消息:bidder ID为空。我使用的是我创建的一个名为getName的函数,我认为这是个问题,但代码中使用的其他地方它运行正常。

int main()
{
    double bid1, bid2;//declare bid1, bid2
    printHeader();
    string lotName= getName("Enter lot name: "); //lot name
    double reservePrice= getPrice("Reserve price: $");
    if (reservePrice<=0) {
        printErrorMessage(5);
        return 0;
    }
    cout<<"n";
    string bidder1= getName("Bidder 1 ID: "); //bidder1 name

    if (bidder1== "") {
        printErrorMessage(3);
        bid1=0;
    }
    else {
        bid1= getPrice("Bidder1 price: $"); //bidder 1 price
        bool lead= isBidPriceGood (bid1, reservePrice); //true if bid1>reservePrice
        if (lead==true)
            cout<<"n"<<bidder1<<" is high bidder, current price = $"<<bid1<<endl<<endl;
    }
    string bidder2= getName("Bidder 2 ID: "); //bidder2 name
    getline(cin,bidder2);
    if (bidder2== "") {
        printErrorMessage(3);
        bid2=0;
    }
    else {
        bid2= getPrice("Bidder1 price: $"); //bidder 2 price
        isBidPriceGood (bid2, reservePrice); //true if bid2>reservePrice
    }
    //function
    string getName(string prompt)
    {
        string name;
        cout<<prompt;
        getline(cin,name);
        return name;
    }


    double getPrice(string prompt)
    {
        string x;
        double price;
        cout<< prompt;
        cin>>price;
        getline(cin,x);
        return price;
    }
    void printErrorMessage(int num)
    {
        if (num == 1) {
            cout << endl
                << "  ERROR: Reserve not met, bid rejected" << endl << endl;
        } else if (num == 2) {
            cout << endl
                << "  ERROR: Negative price, bid rejected" << endl << endl;
        } else if (num == 3) {
            cout << endl
                << "  ERROR: Blank bidder ID, no bid allowed" << endl << endl;
        } else if (num == 4) {
            cout << endl
                << "ERROR: Neither bidder met Reserve, auction canceled" << endl << endl;
        } else if (num == 5) {
            cout << endl
                << "ERROR: Reserve is not positive, auction canceled" << endl << endl;
        } else {
            cout << "   This should never print" << endl << endl;
        }
    }

getline(cin,name)将一直读取到下一行。您可能已经在输入流中等待了一条换行符,这是您以前没有读取换行符的输入。例如,您的cin>>price将读取一个数字,但不会读取该数字之后的换行符,因此,如果对getName的调用之前是对getPrice的调用,则价格之后的换行符号仍将等待,而getName将其视为行的末尾。


为更新的问题编辑:您需要更改此项:

string bidder2= getName("Bidder 2 ID: "); //bidder2 name
getline(cin,bidder2);

仅此而已:

string bidder2= getName("Bidder 2 ID: "); //bidder2 name

你明白为什么了吗?