0

I am trying to create a program which reads from a text file which looks like this:

iPhone11Pro 64 1099 
iPhone11Pro 256 1249 
iPhone11Pro 512 1449 
iPhone11 64 699   
iPhone11 128 749   
iPhone11 256 849   
iPhoneSE 64 399
iPhoneSE 128 449
iPhoneSE 256 549
iPhoneXR 64 599
iPhoneXR 128 649

Then the program should open the file and give the phone a model, capacity, and price.

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <vector>

using namespace std;

struct iPhone
{
    string model;
    int capacity;
    double price;
};

void showList(iPhone model, int cap, double price);

int main()
{
    vector <iPhone> iphones;
    ifstream file("iPhone.txt");
    if (!file)
    {
        cout << "Error Opening File";
    } else {
        string model;
        int cap;
        double price;
        int i = 0;
        cout << left    << setw(15) << "Model" 
                        << setw(15) << "Capacity" 
                        << setw(15) << "Price" << endl;

        while (!file.eof())
        {
            file >> model >> cap >> price;
            iphones.push_back(iPhone());
            iphones[i].model = model;
            iphones[i].capacity = cap;
            iphones[i].price = price;
        }

        for (int i = 0; i < 11; i++)
            {
             cout   << setw(15) << iphones[i].model 
                    << setw(15) << iphones[i].capacity  
                    << setw(15) << iphones[i].price << endl;
            }
    }
    return 0;
}

I am trying to output the model capacity and price and when I do, I get an error code which says vector subscript out of range but it still seems to compile. Can someone please help me with this.

Ok so I ended up moving the for loop out of the while loop but now it seems to only print the last line out to console and leaves zeros for all other values. What can I do to make it properly display the information.

Ondrej K.
  • 7,255
  • 11
  • 17
  • 29
Piklez
  • 13
  • 4
  • Move the `for` loop to after the `while` loop. After you have read the entire file. – Johnny Mopp Sep 04 '20 at 02:21
  • Obligatory: [Why is iostream::eof inside a loop condition (i.e. \`while (!stream.eof())\`) considered wrong?](https://stackoverflow.com/q/5605125) – Johnny Mopp Sep 04 '20 at 02:22
  • With the edit to the question, the title is not a good description of your problem anymore. – 1201ProgramAlarm Sep 04 '20 at 03:20
  • In its current form, you are never advancing the index `i` when reading in the data and keep clobbering over the first entry, add: `i++;` before end of the while loop block for instance. – Ondrej K. Sep 06 '20 at 11:02

0 Answers0