简体   繁体   中英

Reading from the next line in a file c++

I'm trying to make an inventory system that reads from a list and stores things in parallel vectors. My vectors are set up as public members in a class that I have included in my code. The text file looks like this

1111
Dish Washer
20 250.50 550.50
2222
Micro Wave
75 150.00 400.00
3333
Cooking Range 
50 450.00 850.00
4444
Circular Saw
150 45.00 125.00
6236
Tacos
200 5.00 5.50

Here is my code

 int main()
{
    char choice;
    Inventory Stocksheet(5); // the included list has 5 items if a text file has more then it should scale fine
    int id, ordered;
    string name;
    double manuprice, price;
    ifstream data;
    data.open("Inventory Data.txt");
    if (data.fail())
    {
        cout << "Data sheet failed to open \n";
        exit(1);
    }
    while (data >> id )
    {
        Stocksheet.itemID.push_back(id);
        getline(data,name);
        Stocksheet.itemName.push_back(name); // this is where my code fails
        data >> ordered;
        Stocksheet.pOrdered.push_back(ordered);
        Stocksheet.pInstore.push_back(ordered);
        data >> manuprice;
        Stocksheet.manuPrice.push_back(manuprice);
        data >> price;
        Stocksheet.sellingPrice.push_back(price);
    }

    do
    {
        cout << "     Your friendly neighborhood tool shack\n";
        cout << "Select from the following options to proceed \n";
        cout << "1. Check for item \n";
        cout << "2. Sell an iem \n";
        cout << "3. Print Report \n";
        cout << "Input any number other than 1,2 or 3 to exit \n";
        cout << "Selection : ";
        cin >> choice; // think about sstream here
        switch (choice)
        {
        case '1': checkforitem(Stocksheet);
            break;
        case '2': sellanitem(Stocksheet);
            break;
        case '3': printthereport(Stocksheet);
            break;
        default: cout << " ^-^ Exiting the shop. Have a fantastic day! ^-^ \n";
            break;
        }

    }while ((choice == '1') || (choice == '2') || (choice == '3'));
    data.close();
    return 0;
}

I commented where my code breaks. In the while loop the number id is pushed to my first vector but the name is blank and every value after that is left blank. Is there something wrong with how my loop is set up?

When you use the >> operator you get a "word" type thing. It stops on whitespace. So then when you call getline , it reads the newline at the end of the first line (with the id on it) and stops. So your name is blank.

You can call data.ignore() before you switch to getline and that will take care of the newline. Be careful mixing the >> operator with getline . It doesn't do what you'd expect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM