0
case 4:
        {
            string bookTitleDel;
            int bookPageNDel;
            int bookReviewDel;
            float bookPriceDel;

            cout << "\nPlease Enter the Title to be Deleted: ";
            cin >> bookTitleDel;
            cout << "\nTotal Number of Pages of the Book to be Deleted: ";
            cin >> bookPageNDel;
            cout << "\nPlease Enter Rating (stars): ";
            cin >> bookReviewDel;
            cout << "\nPlease Enter Price: ";
            cin >> bookPriceDel;

            for(int i=0;i<MAX_BOOKS;i++)
            {
                if((books[i].bookTitle!=bookTitleDel) && (books[i].bookPageN!=bookPageNDel) && (books[i].bookReview!=bookReviewDel) && (books[i].bookPrice!=bookPriceDel))
                {

                    cout<<"\n\nBook Doesnt Exist\n";
                    continue;

                }

            }

            for(int i=0; i<MAX_BOOKS; i++)
            {
                if((books[i].bookTitle==bookTitleDel) && (books[i].bookPageN==bookPageNDel) && (books[i].bookReview==bookReviewDel) && (books[i].bookPrice==bookPriceDel))
                {
                    a=i;
                    books[i]= {};
                    cout << "\nBook Deleted\n";
                    for(int k=a; k<MAX_BOOKS-1; k++)
                    {
                        books[k]=books[k+1];
                    }
                    break;
                }

            }

            break; //break to exit switch case #4.

如果不存在,此代码将打印 10 次“书不存在”。如何避免?我正在将输入的值与我已经使用此处未显示的“添加书”选项添加的值进行比较。

4

2 回答 2

5

仅当没有条目匹配时才想打印“书籍不存在”,而不是每次都不匹配时打印。

因此,如果有匹配项,则将布尔变量设置为 true(并中断),如果循环结束后没有匹配项,则打印。

编辑:伪代码

        boolean foundMatch = false;
        for(int i=0;i<MAX_BOOKS;i++)
        {
            if((books[i].bookTitle==bookTitleDel) && (books[i].bookPageN==bookPageNDel) && (books[i].bookReview!=bookReviewDel) && (books[i].bookPrice==bookPriceDel))
            {
                foundMatch = true;
                break;
            }
        }
        if (!foundMatch)
        {
            cout<<"\n\nBook Doesnt Exist\n";
        }

顺便说一句,您的代码中有一个错误。如果相等的条件是a1 == a2 && b1 == b2 && c1 == c2,那么它的否定(如果为真,则为假)是!(a1 == a2 && b1 == b2 && c1 == c2)NOT a1 != a2 && b1 != b2 && c1 != c2

于 2013-02-06T03:37:51.067 回答
0

代替 2 个 for 循环,使用一个 for 循环并使用 Patashu 所说的布尔变量。

    switch = false

    for(int i=0; i<MAX_BOOKS; i++)
    {
        if((books[i].bookTitle==bookTitleDel) && (books[i].bookPageN==bookPageNDel) && (books[i].bookReview==bookReviewDel) && (books[i].bookPrice==bookPriceDel))
        {   
            switch = True
            a=i;
            books[i]= {};
            cout << "\nBook Deleted\n";
            for(int k=a; k<MAX_BOOKS-1; k++)
            {
                books[k]=books[k+1];
            }
            break;
        }

    }
    if (switch == False)
     cout<<"\n\nBook Doesnt Exist\n";
于 2013-02-06T03:52:02.237 回答