Answered by:
Read file into Array

Question
-
Hello All,
I am trying to get the contents of a text file into a multi-dimensional array so I can then access its contents by index for calculations such as getting the PLU code and quantity to determine what product is sought and the total price. My code so far is as follows
[code]
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;int main ()
{
int pluCode;
string prodName;
int prodSalesType;
double purchaseQty;
double unitPrice;
double inStock;
double total;
string products;
string myArray[22][5];
int rows = 22;
int columns = 5;string line;
ifstream myfile ("inventory.txt");
if (myfile.is_open())
{
cout << "Here is our inventory:\n" << endl;while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}//myFile >> products;
myArray[rows][columns] = myFile;cout << "\nPlease enter the PLU Code for the produce you wish to buy: \n";
cin >> pluCode;if (pluCode == 4028 || pluCode == 4252)
{
cout << "Please enter the amount you would like to buy: ";
cin >> purchaseQty;
total = purchaseQty * unitPrice;
}else if (pluCode == 4249)
{
cout << "Please enter the amount you would like to buy: ";
cin >> purchaseQty;
total = purchaseQty * unitPrice;
}else
{
cout << "Please enter the weight you would like to buy in lbs: ";
cin >> purchaseQty;
total = purchaseQty * unitPrice;
}
myfile.close();
}else cout << "Unable to open file";
system("pause");
return 0;
}[/code]
...two rows of the contents of the file is as follows;
4101 BRAEBURN_REG 1 0.99 101.5
4021 DELICIOUS_GDN_REG 1 0.89 94.2I will appreciate any assistance.
Thanx.
Monday, March 5, 2012 1:59 AM
Answers
-
>I had to redo the entire thing with arrays which I don't
>really know how to work with since I am still trying to
>learn it. ... I need help with working with the array data
Then you should ask your instructor/teacher for a review.
The assignments are intended to find out how well you
are doing in understanding the material. Getting others
involved extensively subverts that end.
Additionally, there are many online tutorials which
explain using "raw" arrays in some detail. You should
use your initiative and seek them out. This one is
quite comprehensive:
ptrtutor.txt
"A Tutorial on Pointers and Arrays in C"
http://www.programmersheaven.com/download/16622/688/ZipView.aspx
- Wayne- Proposed as answer by Jesse Jiang Monday, March 19, 2012 9:16 AM
- Marked as answer by Jesse Jiang Wednesday, March 28, 2012 7:28 AM
Tuesday, March 6, 2012 6:16 PM
All replies
-
You really need to go back and review your training material.
Where do you open myFile?
Your first while loop repeatedly reads data from myfile into line. When you finally exit the loop, what will be the contents of line? Surely you need to process more data than just the last line of the file.
myArray[i][j] is a string. myFile is an ifstream. Are the types compatible? Are you allowed to store the value contained in an ifstream (not the data in the file it refers to) into a string?
myArray is an array of 22 array of 5 string. The first element is myArray[0][0]. The last is myArray[21][4]. But rows and columns are initialized to 22 and 5, respectively, so you are trying to store into a non-existent element of the array.
You multiply purchaseQty by unitPrice. Where is a value ever storedin unitPrice?
How can the if, the else if, and the else ever produce a different value.
While you are reworking your code, learn to indent consistently using spaces, not tabs. VC has an option to do that for you.
Monday, March 5, 2012 2:39 AM -
Hi tech
I can not get what your program is supposed to do. Can you try to explain in some detail what you are trying to achieve with your program? The program of yours does not reflect your brief specification.
Best regards
Chong
Monday, March 5, 2012 7:52 AM -
Hi.
It's not a very good idea to use text files for such purpose. When the file becomes bigger you will get a performance issue. And if it reaches the size of 2gb it will not work on FAT file system. It's better to use a data base system.
Also if you nevertheless will use a file don't load all of it to memory. For example make std::map with product ID as a key and total price as a value. Then just go through the file and increase total price every time you find a record with particular product ID.
Monday, March 5, 2012 12:43 PM -
Hi.
It's not a very good idea to use text files for such purpose. When the file becomes bigger you will get a performance issue. And if it reaches the size of 2gb it will not work on FAT file system. It's better to use a data base system.
For a homework assignment??Monday, March 5, 2012 8:05 PM -
I am going with a different approach than earlier posted and I can successfully read data and run calculations but it seems that the calculations are taking values from the last line read from the file when it should read values for the line corresponding to the PPLU code entered. Here is my current code;
[code]
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;void outputLine(int, string, int, double, double);
int pluCode;
string prodName;
int prodType;
double prodPrice;
double inStock;
double quantity; //used for quantity in weight or count regardless of prodType
double subtotal;
double totalPurchase = 0;int main()
{ifstream inClientFile( "inventory.txt", ios::in );
if( !inClientFile )
{
cerr << "File \"" << "inventory.txt" << " \"could not be opened for input!" << endl;
exit( 1 );
}cout << "Here is our inventory: " << endl;
cout << "\n";while( inClientFile >> pluCode >> prodName >> prodType >> prodPrice >> inStock )
{
cout << pluCode << ' ' << prodName << ' ' << prodType << ' ' << prodPrice << ' ' << inStock << endl;
}/*double checkout()
{*/
while (pluCode != -1)
{
cout << "\n";
cout << "Please enter the PLU code for the produce you would like to buy: ";
cin >> pluCode;if (pluCode == -1) //checkf input for exit sign
{
return 0;
}cout << "\n";
cout << "Please enter the quantity of the produce you would like to buy: ";
cin >> quantity;subtotal = prodPrice * quantity;
totalPurchase += subtotal;
inStock -= quantity;
if (inStock < quantity) //check for quantity in stock
{
cout << "Sorry, this product is out of stock. Please try later." << endl;
}else
cout << pluCode << ' ' << prodName << ' ' << subtotal << endl;if (totalPurchase > 50) //check for
{
totalPurchase -= subtotal * .05;
cout << "After a 5% discount, your total purchase is " << totalPurchase << endl;
}else
cout << "Your total purchase is " << totalPurchase << endl;
}//end while
//}//end functionsystem("pause");
return 0;
}[/code]
Thanx,
Monday, March 5, 2012 10:47 PM -
Your new code has many of the same problems your original code did, specially the while loop.Monday, March 5, 2012 11:49 PM
-
Okay, so I had to redo the entire thing with arrays which I don't really know how to work with since I am still trying to learn it. I need help with working with the array data on each line to be able to display, do some calculations and update into a new file;
4101 BRAEBURN_REG 1 0.99 101.5
4021 DELICIOUS_GDN_REG 1 0.89 94.2[code]
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int pluCode;
string prodName;
int prodType;
double prodPrice;
double inStock;
double quantity; //used for quantity in weight or count regardless of prodType
double subtotal;
double totalPurchase = 0;
int main ()
{
string array[22];int loop=0; //loop for input
string line; //container for the data read from the file
ifstream myfile ("inventory.txt");if (myfile.is_open()) //if the file is opens succesfully
{
while (! myfile.eof() ) //while the end of file is NOT reached
{
getline (myfile,line); //get one line from the file
array[loop] = line;
cout << array[loop] << endl; //and output it
loop++;
}
myfile.close(); //closing the file
}
else cout << "Unable to open file"; //if the file is not open output
//double checkout();
system("PAUSE");
return 0;
}
/*checkout()
{
}*/
[/code]
- Edited by techiegzz Tuesday, March 6, 2012 11:39 AM
Tuesday, March 6, 2012 11:36 AM -
Hi techiezz
The following lines in your program should be rewritten:
while (! myfile.eof() ) //while the end of file is NOT reached
{
getline (myfile,line); //get one line from the file
array[loop] = line;
cout << array[loop] << endl; //and output it
loop++;
}with the following:
while (1){
if (!getline(myfile,line)){
if (infile.eof())break;//break from while
cout<<"File read failed"<<endl;
exit(-1);
}//if
array[loop] = line;
cout << array[loop] << endl; //and output it
loop++; } //whileTuesday, March 6, 2012 1:52 PM -
Okay, so I had to redo the entire thing with arrays which I don't really know how to work with since I am still trying to learn it. I need help with working with the array data on each line to be able to display, do some calculations and update into a new file;
What is your question exactly? Only you know what your program is supposed to do.
BTW, the correct way to read a file line-by-line is
while (getline (myfile, line))
{
array[loop] = line;
cout << array[loop] << endl;
loop++;
}
if (!myfile.eof())
{
// something went wrong
}
If you want to parse each line, I would suggest using std::istringstream.
David Wilkinson | Visual C++ MVPTuesday, March 6, 2012 2:34 PM -
Okay, the program is supposed to read an inventory file into arrays, then while the customer wants to continue shopping, ask for PLU code (first item on each line) and quantity (last item on the each line) to calculate the subtotal (to derive the totalPurchase at the end of d application) while keeping track of inventory per item. When user chooses to exit, a file is created and the updated inventory information for all the listed items is written into this file. If I can access the items on each line of the arrays, I think I can get somewhere.
- Edited by techiegzz Tuesday, March 6, 2012 3:41 PM
Tuesday, March 6, 2012 3:34 PM -
Okay, the program is supposed to read an inventory file into arrays then, while the customer wants to continue shopping, ask for PLU code and quantity to calculate the subtotal (to derive the totalPurchase at the end of d application) while keeping track of inventory per item. When user chooses to exit, the updated inventory for all the listed items in a different file.
One way to do this is to define a struct for each entry
struct Item
{
int field1;
string field2;
int field3;
double field4;
double field5;
};
I would use better names, but I don't know what the fileds in the file are.
Item items[22];
int loop = 0;
while (getline (myfile, line))
{
Item& item = items[loop];
istringstream is(line);
is >> item.field1 >> item.field2 >> item.field3 >> item.field4 >> item.field5;
if (!is)
{
// something went wrong
}
loop++;
}
if (!myfile.eof())
{
// something went wrong
}
David Wilkinson | Visual C++ MVPTuesday, March 6, 2012 4:05 PM -
The last code you posted did not have any arrays.Tuesday, March 6, 2012 4:06 PM
-
Okay, the program is supposed to read an inventory file into arrays then, while the customer wants to continue shopping, ask for PLU code and quantity to calculate the subtotal (to derive the totalPurchase at the end of d application) while keeping track of inventory per item. When user chooses to exit, the updated inventory for all the listed items in a different file.
One way to do this is to define a struct for each entry
struct Item
{
int field1;
string field2;
int field3;
double field4;
double field5;
};
I would use better names, but I don't know what the fileds in the file are.
Item items[22];
int loop = 0;
while (getline (myfile, line))
{
Item& item = items[loop];
istringstream is(line);
is >> item.field1 >> item.field2 >> item.field3 >> item.field4 >> item.field5;
if (!is)
{
// something went wrong
}
loop++;
}
if (!myfile.eof())
{
// something went wrong
}
David Wilkinson | Visual C++ MVPSorry, here are a couple of lines on the file;
4101 BRAEBURN_REG 1 0.99 101.5
4021 DELICIOUS_GDN_REG 1 0.89 94.2...and the task specifcally said to use arrays since in a sbsequent task we have to build on the arrays used in this task.
Tuesday, March 6, 2012 5:13 PM -
>I had to redo the entire thing with arrays which I don't
>really know how to work with since I am still trying to
>learn it. ... I need help with working with the array data
Then you should ask your instructor/teacher for a review.
The assignments are intended to find out how well you
are doing in understanding the material. Getting others
involved extensively subverts that end.
Additionally, there are many online tutorials which
explain using "raw" arrays in some detail. You should
use your initiative and seek them out. This one is
quite comprehensive:
ptrtutor.txt
"A Tutorial on Pointers and Arrays in C"
http://www.programmersheaven.com/download/16622/688/ZipView.aspx
- Wayne- Proposed as answer by Jesse Jiang Monday, March 19, 2012 9:16 AM
- Marked as answer by Jesse Jiang Wednesday, March 28, 2012 7:28 AM
Tuesday, March 6, 2012 6:16 PM -
Sorry, here are a couple of lines on the file;
Yes, I saw the file format before -- that is how I chose the types in the struct.
4101 BRAEBURN_REG 1 0.99 101.5
4021 DELICIOUS_GDN_REG 1 0.89 94.2
...and the task specifcally said to use arrays since in a sbsequent task we have to build on the arrays used in this task.
The code I showed you has an array of structs.
David Wilkinson | Visual C++ MVPTuesday, March 6, 2012 6:21 PM