如何避免一遍又一遍地打印同一件事?

时间:2013-02-06 03:35:57

标签: c++ arrays for-loop

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次,如果它不存在的话。怎么避免呢?我将输入的值与我已添加的值与此处未显示的“添加书籍”选项进行比较。

2 个答案:

答案 0 :(得分:5)

只有当条目中没有条目匹配时才打印'Book Is Not Exist',而不是每次都没有匹配。

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

编辑:伪代码

        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

答案 1 :(得分: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";