-
Query file compare data
Here is my dilemma, I have a snippet of code that I have written to extract data from a file and print it to the screen. It works well.
But now I want to only display lines of the file based on certain
column values in the text. In other words, each line in the file has
29 columns broken down into 5 for an ID, 15 for a name, 3 for a qty, 3for a reorder point, and 3 for the order size.
When the qty columns drop below that of the reorder point I would like to print that to the screen. I am new to C++ and have read the fstream txt's and others I am lost.
Here is my code and file I am pullingfrom. Thanks in advance.
// reading the stock.dat file
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
int main()
{
char buffer [256];
ifstream stock ("stock.dat");
if (! stock.is_open())
{
cout << "Error opening file";
exit (1);
}
while (! stock.eof() )
{
stock.getline (buffer,100);
cout << buffer << endl;
} return 0;
}
- Contents of stock.dat file -
BKT01Prunes 015020025
BKT05Pears 032020025
BKT07Peaches 011020025
-
Can you reformate the input file?
If this is a project where you must use that specified input, you need to parse each line, by looping through that buffer you read in each loop.
After you read a line using getline the first 5 chars of buffer are the id. Then comes the name, which ends with a space. Then you have the 3 numbers, all together. You will have to break these apart. ie first 3 chars after the space represent the quanity. the next 3 represent the reorder point, and the remaining 3 are the order size.
I would reformat the input file to look like this
BKT01 015 020 025 Prunes
BKT05 032 020 025 Pears
BKT07 011 020 025 Peaches
Declare the vars
char id[6],name[100];
int qty,reorder,size;
Then to read in a line do this.
stock >> id; //read in the id
stock >> qty >> reorder >> size; //read these in as ints
stock.getline(name,99,'\n'); //get the rest of the line which is the name
Put that code inside your while loop, and use the reformatted input file. Now you can do
if( qty <= reorder )
{
cout << "You should order " << size << " units of " << name << " now!!" << endl;
}
Code:
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
int main()
{
char id[6],name[100];
int qty,reorder,size;
ifstream stock ("stock.dat");
if (! stock.is_open())
{
cout << "Error opening file";
exit (1);
}
while (! stock.eof() )
{
stock >> id; //read in the id
stock >> qty >> reorder >> size; //read these in as ints
stock.getline(name,99,'\n'); //get the rest of the line which is the name
if( qty <= reorder )
{
cout << "You should order " << size << " units of " << name << " now!!" << endl;
}
} //end while loop
return 0;
}
Using this as stock.dat
BKT01 015 020 025 Prunes
BKT05 032 020 025 Pears
BKT07 011 020 025 Peaches
-
Rpi, excellent expalanation. This is good stuff. Thanks