user1896464
user1896464

Reputation: 345

Read from a file. C++

SO when my program starts, it attempts to read a list of products from a file. but if the file does not exist it displays an error and continue on. the problem im having is when it displays the error, it doesnt continue on to the do while loop

ifstream input;
    input.open("data.txt");


    if (input.fail())
    {
        cout << "\n Data file not found \n";
    }
    ListItemType data; 

    input >> data.productname;
    while(( !input.eof()))
    {
        input >> data.category;
        input >> data.productprice;
        addproduct(head, data); 
        input >> data.productname;
    }

    input.close();

Upvotes: 0

Views: 112

Answers (1)

Tony Delroy
Tony Delroy

Reputation: 106068

It's not identical functionality, but it's generally better to move towards something like:

if (std::ifstream input("data.txt"))
{
    ListItemType data; 
    while (input >> data.productname >> data.category >> data.productprice >> data.productname)
        addproduct(head, data);
    if (!input.eof())
        std::cerr << "Error parsing input file.\n";
}    
else
    cout << "\n Data file not found \n";

If you structure your if/else clauses as above, whatever happens it will continue to the following code as you'd like.

Note that the code above checks for a problem after each input operation. Your code tries to read data.productprice even if reading data.category failed. It's kind of weird you're reading productname twice, and I'm assuming you can call addproduct after the I/O - if not you'll need a while loop like:

    while (input >> data.productname >> data.category >> data.productprice)
    {
        addproduct(head, data);
        if (!(input >> data.productname))
            break;
    }

Upvotes: 1

Related Questions