0

so I have to create a code where I'm reading from two files, inventory and order. I have compare the order and get the number of items were fulfilled and the total amount. This program below satisfies all that's needed however, I have to use eof() and I don't know how. The lines before this part of the program just simply reads the files and imports the information of the file to instream1 and instream2 which are internal names for the files. Thank you so much in advance.

for(int i=0;i<ord;i++){ 
    for(int j=0;j<inv;j++){ 
        if(prod_ord[i] == prod_code[j])       
            {
            if(order[i] <= units[j])
            {
                fullfill[i]= order[i];
                amt_billed[i] = fullfill[i] * unitprice[j];
            }
            else
            {
                fullfill[i]= units[j];
                amt_billed[i] = fullfill[i] * unitprice[j];
            }               
            }
        else
            {
                cout<< "Order invalid."<<endl;
    }
    }

}

float total_due = 0;

cout<< "Order#: order0923\nSalesman: full name\n \t Fullfilled \t Amt Billed" <<endl;
    for(int i= 0;i<ord;i++)
    {
        cout<< prod_ord[i]<<" \t"<<fullfill[i]<<" \t"<<amt_billed[i]<<endl;
        total_due += amt_billed[i];  
    }
cout<<"Total Due: $"<<total_due<<endl;
xparada
  • 1
  • 1

1 Answers1

1

If you’re using eof(), you probably mean using it to figure out when to stop reading input. That is, you want your termination condition, the second clause of the for loop, to call eof(). Not a complete solution, because this looks like homework, but there are basically two equivalent approaches:

for (records = 0; !std::cin.eof(); ++records) {
  // Parse a record and store it, preferably in a vector.
  // The records variable stores the number of records.
}

And:

int records = 0;
while (!std::cin.eof()) {
  // Read in and store a record, preferably in a vector.
  ++records;
}

But Take Note

Note that either of these will fail if the input contains an EOF while reading a record. So you really want something like (untested):

bool read_record( std::istream&, record_t& );
using std::cin;
constexpr size_t SOME_REASONABLE_NUMBER = 4096U/sizeof(record_t);
std::vector<record_t> recordv;
recordv.reserve(SOME_REASONABLE_NUMBER);

while (cin.good()) {
  record_t this_record;

  if (read_record(cin, this_record))
    recordv.push_back(this_record);
  else
    break;
}

If you’re using built-in types or overloading std::istream::operator>>, record_t this_record; while (cin >> this_record) will work. (It returns a reference to cin, which evaluates to true if there are no errors on the stream. It does not check EOF, but the next iteration would fail.)

Davislor
  • 12,287
  • 2
  • 26
  • 36