Help - Read data from a file to array

This is my code:

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;

void load(string[], string[], double[], int[]);
void ShowItems(string[], string[], double[], int[]);
const int ARRAY_SIZE = 525;

int main()
{
string itemCode[ARRAY_SIZE] = { "" };
string itemDescription[ARRAY_SIZE] = { "" };
double itemPrice[ARRAY_SIZE] = { 0 };
int itemQty[ARRAY_SIZE] = { 0 };
load(itemCode, itemDescription, itemPrice, itemQty);
ShowItems(itemCode, itemDescription, itemPrice, itemQty);
}

void load(string code[], string description[], double price[], int qty[])
{
ifstream fin;
fin.open("C:\\classdata\\inventory.txt");
int j = 0;
while (j<ARRAY_SIZE && getline(fin, code[j]))
{
j++;
}
j = 0;
while (j<ARRAY_SIZE && getline(fin, description[j]))
{
j++;
}
j = 0;
while (j<ARRAY_SIZE && fin >> price[j])
{
j++;
}
j = 0;
while (j<ARRAY_SIZE && fin >> qty[j])
{
j++;
}
}

void ShowItems(string code[], string description[], double price[], int qty[])
{
cout << " | " << setw(7) << "Codes" << " | " << setw(15) << "Descriptions" << " | " << setw(8) << "Prices" << " | " << setw(10) << "Quantity" << endl;
int i = 0;
while (i<ARRAY_SIZE&&code[i].size()>0)
//for(int i=0; i<ARRAY_SIZE; i++)
{
cout << " | " << setw(7) << code[i] << " | " << setw(15) << description[i] << " | " << setw(8) << price[i] << " | " << setw(10) << qty[i] << endl;
if ((i + 1) % 20 == 0)
{
cin.get();
cout << " | " << setw(7) << "Codes" << " | " << setw(15) << "Descriptions" << " | " << setw(8) << "Prices" << " | " << setw(10) << "Quantity" << endl;
}
i++;
}
cout << "\n\nPress enter to quit";
cin.get();
}

Current line 26: (j<ARRAY_SIZE && getline(fin, code[j]))

The code works fine; however, if I change line 26 to ( getline(fin, code[j]) && j<ARRAY_SIZE) the code stop working.
Can someone explain why?
Thank you.

This is the result of short-circuit evaluation. In C++ (and many other languages), the "&&" operator will check the first boolean expression and then if and only if it evaluates to true, check the second boolean expression.

So, if you check that j is in range before using it (ie, j<ARRAY_SIZE && getline(fin, code[j]))), you do not get an out of bounds error. If you do it the other way, on the last iteration of the loop j will be out of bounds and getline(fin, code[j]) will throw an error and cause the program to stop.

EDIT: Short-circuit evaluation does not apply solely to the && operator, but the logic is the same for others. So, in the case of the below, B will only be evaluated if A is false. If A is true, then the || operator will return true regardless of the state of B so there is no reason to evaluate B.
if(A || B) { // Do the sterfs }...
Last edited on
Thank you so much sir.
This really helps
Topic archived. No new replies allowed.