书架数据结构问题

时间:2019-03-24 19:49:29

标签: c++ vector data-structures

我正在制作宽度为s(1

我面临的问题是,当var ='E'时,程序应在书架上显示剩余的书,然后退出该问题并转到其他问题,但是当输入'E'时,书架上的剩余书将不会显示,并且程序不会退出。我试图弄乱嵌套在整个while循环中的while循环条件。

#include <iostream>
#include <vector>

using namespace std;

struct book{
    int id;
    int w;
};

int main(){
//std::vector::~vector
    //create instance of book
    book my_book;
    //initialize the placeholders
    int s, removed_book, back_width;
    char var;
    //create the vector 
    vector<book>shelf;
    while(true){
        //enter the s value 
        s = 0;
        cout << "enter the s value: " << endl;
        cin >> s;
        int w_total = 0;

        //be able to exit the program
        if(s == -1){
            return 0;
        }
        int x = 1;
        //while remaining space
        while(x!=0){              //need to fix this up

            cout << "enter the action(A,R,E): " << endl;
            cin >> var >> my_book.id >> my_book.w;


            //if A
            if(var == 'A'){
                //get info about the book
                /*
                cout << "enter id: " << endl;
                cin >> my_book.id;
                cout << "width(w): " << endl;
                cin >> my_book.w;
                */
                w_total += my_book.w;
                shelf.insert(shelf.begin(),my_book);
                cout << "total width(1): " << w_total << endl;

                if(w_total > s){
                    while(w_total >= s){
                        //remove the rightmost(back) book
                        w_total = w_total - shelf.back().w;
                        cout << "total width(2): " << w_total << endl;
                        shelf.erase(shelf.end()-1);
                    }
                }
            }
            //if R
            else if(var == 'R'){
                //cout << "which book to be removed? : " << endl;
                //cin >> removed_book;
                removed_book = my_book.id;
                for(int i = 0; i < s; i++){
                    if(shelf[i].id == removed_book){
                        shelf.erase(shelf.begin()+i);      
                    }
                }
            }
            //if E
            else if(var == 'E'){
                cout << "remaining books on shelf: " << endl;
                for(int i = 0; i < shelf.size(); i++){
                    if(shelf[i].id!=0){
                        cout << "id: "<<shelf[i].id << endl;
                    }   
                }
                //maybe put the display in here?
                x = 1;  
            }
        }
        //print out the remaining shelf

        shelf.clear(); 
        //erase the shelfs(vectors) contents
        //increase problem number
    }
return 0;
}

预期输出:

10(shelf width)
A 1 3(Add id width)
A 2 5
E
-->PROBLEM 1: 2 1

1 个答案:

答案 0 :(得分:2)

cin >> var >> my_book.id >> my_book.w要求用户输入三项内容:一个字符和两个整数。您必须先输入所有三个,然后才能检查var中的操作并对其采取行动。