Solved

Pulling data from a file, and formating it.

Posted on 2000-03-07
20
396 Views
Last Modified: 2011-09-20
What I want to do,
is read data from a file, but when it prints on screen, have it formatted into columns. Is there an easy way to di this?

When I tried to do it, I get my headings that i put in, then instead of the data in the file, it prints just a bunch of characters and junk.

I think i have all of my variables as the corrct data types, Any suggestions?
0
Comment
Question by:katdude
  • 11
  • 9
20 Comments
 
LVL 22

Accepted Solution

by:
nietod earned 350 total points
ID: 2592711
Its not hard to do at all, but you haven't given us any details of the specifics, an example might be

fstream Fil("File.Txt",ios_base::in);
int x1, x2, x3;

while (!Fil.eof())
{
   Fil >> x1 >> x2 >> x3;
   cout << setw(10) << x1 << setw(10) << x2 << setw(10) << x3 << endl;
}
0
 
LVL 22

Expert Comment

by:nietod
ID: 2592716
If you can give use more details about the format of the file you are reading and printing, we can be more specific.  

better yet, you could post your code and we might be able to explain why it  doesn't work and what you can do to fix it.
0
 

Author Comment

by:katdude
ID: 2593530
I am trying to write a program that will create invoices from a text file, and output the information in the program.

OK here is what i have

#include<stdlib.h>
#include<fstream.h>
#include<iomanip.h>
#include<iostream.h>
#include<math.h>
void main()
{ const int MAX=40;
        char invoice[MAX];

     int store[4];      // store number
     char customer[10]; //customer name
     int credit[10];    //credit card number
        int item[5];       // item number
     int qty[4];        // quantity of items

     float unitPrice[6];     // price of the unit
     float extendedPrice[6]; //total price of all units
     float tax[5];           // applicable sales tax
int totalTax=0,         // total tax
    amountDue = 0,      // full amount of sale including tax
    netSales =0, i =0;  // net sale


ifstream input("c:\\Lab3data.txt");      //read text file

if (!input)  // incase of problems opening the file
  { cout << " Cant open the file.\n\n"; exit(-1);}//end if

  //while (input)
  for (i = 4; i < 10; i++)
  {   input.getline(invoice, MAX);
  cout << "\n _______________________________________________________________";


  cout << "\n\n Store: "<< store[4] << "\n\n";
  cout << " Credit Card Number: " << credit[10] << endl;
  cout << " Customer Name: "      << customer[30] <<"\n\n";

  cout << " Item"       << setw(16)
       << "Quantity" << setw(16)
       << "Unit Price"<< setw(22)
       << "Extended Price " << "\n " ;



  cout << setiosflags( ios::showpoint | ios::fixed)
  << setprecision(2)<< item[5] << setw(8)<< qty[4]
  << setw(17) << unitPrice[6] << setw(17)
  << extendedPrice[6] << setw(10)
  << "TAXABLE\n\n";   //message indicates that item is taxable


   //netSales = (unitPrice) * (qty);
   //totalTax = (tax) * (100);
   //amountDue = netSales + totalTax;
  cout << setw(30) << "Net SALES " << setw(15) << netSales << endl;
  cout << setw(24) << "Tax " << "%" << setw(20) << totalTax <<endl;
  cout << setw(39) << "Amount Due " << setw(6) << amountDue << endl;

  cout << "\n _______________________________________________________________";


  }// end while
}//end main
0
 

Author Comment

by:katdude
ID: 2593533
here is what is in the text file, if it helps;

101  8.25
343 Johnson  2 1234567890
23 5 10.5 N
2 10 5.27 Y
26 Brown 4 0
114 50 1.92 N
567 41 2.53 N
26 72 4.95 Y
243 13 2.05 N
1421 Brokner 1 32156
572 100 55.23 T
-1 end 0 0
102 7.25
1002 McCorkle 3 654987
756 55 17.95 N
2341 10 4.05 N
10 74 3.47 N
2045 Armstrong 6 0
53 25 6.78 N
243 10 9.99 T
102 24 2.95 T
47 12 2.6 N
231 90 1.61 T
666 100 23.95 N
-20 store2 0 0
9999 10.45
811 Taylor 2 5879244
2094 20 15.42 T
4001 5 4.65 T
-100 store3 0 0
104 6.78
1 Carry 3 9856
33 60 7.33 T
44 5 12.95 N
55 15 3.42 N
2 Davis 4 0
654 10 2.95 N
6587 2 98.56 N
215 7 37.98 N
23 19 5.34 T
3 Smith 1 9876531
87 32 8.50 N
-111 end 0 0
 
0
 
LVL 22

Expert Comment

by:nietod
ID: 2593745
First of all, unless you are on an older compiler the files

#include<fstream.h>
#include<iomanip.h>
#include<iostream.h>

have been replaced with

#include<fstream>
#include<iomanip>
#include<iostream>

(As have most of the other C++ (not C) include files.  You will get better results with the new files.  One difference is that the names they define are in the "std" namespace.  So you mist prefix the names with "std::" like

std::ifstream input("c:\\Lab3data.txt");

If you don't like all those "std::"s running around, you can drop then and place a "using namespace std;" statement at the top of the program.

continues
0
 
LVL 22

Expert Comment

by:nietod
ID: 2593755
Now the file looks complex.  it appears to be composed of sections like

343 Johnson  2 1234567890
23 5 10.5 N
2 10 5.27 Y

where the first line has:

1. an integer number--what is this number?
2. a name
3. an integer number that appears to define the number of lines that will folliow--Is that correct?
4. another number--what is it?

then you have a number of lines whose count is specified by item 3 above.
Each line has

1. an integer--What?
2. another integer--What?
3. A decimal number--what?
4. A yes/no switch letter--For what?

Can you provide a little more details about this format?
0
 

Author Comment

by:katdude
ID: 2606721
Adjusted points to 300
0
 

Author Comment

by:katdude
ID: 2606722
1st number is the store number 101

2nd number is the tax rate 8.25%

3rd number is a customer number 343

then the customers name is "Johnson"

next number the (4th) is the number of sales for that customer

the 6th number is a credit card number.

the next (7th) number is the item record number,

8th number is the Quantity of items sold,

9th number is the Price for the item,

next I have a function to calculate the total for the items in this row.

Next,
If there is an "N", here it means the items are not taxable.
 If there is a "Y", then a message Taxable is printed to the screen.
(this is the end of this line)

Then the next line is, item record number, Quantity of items sold, Price for the item, followed by the total for this customer.

the 26 is the store number, followed by Customers name, etc.. just like before.

it continues until it reads the -1
then it is supposed to continue with the next invoice.

this is done until the end of this file is completed. then I have to calculate all of the total sales, and taxes etc...
---------------------------------------
My problem is getting the amounts in the right places.

If its possible, i would like to format it to look like this;

---------------------------------------
Store: 101

Credit card #: 1234567890

Customer name: Johnson

Item  Qty  Unit Price  Extended Price
 23    5     10.50        ?    
  2   10     10.27        ?    Taxable

        Net sales         ?
        Tax rate 8.25%    ?  
             Amount Due   ?
----------------------------------------

(here it would go to the next customer)
until it reaches eof

then at the end of all invoices i will calculate the total sales, tax, etc...



 




 
0
 
LVL 22

Expert Comment

by:nietod
ID: 2606803
This is probably not perfect, but is much improved. Why don't you fool with this and then get back to me if you need more help.  Compare it with yours to see the changes I made.

#include<stdlib.h>
#include<fstream>
#include<iomanip>
#include<iostream>
#include<math.h>
#include<string>

using namespace std;

int main()
{
   string invoice;
   // This should have been "char store[4]", not "int store[4]"
   // but an int work even better.
   int    store;           // store number
   float  taxrate;         // tax rate.

   float extendedPrice; //total price of all units
   float tax;           // applicable sales tax

   int totalTax=0,         // total tax

   amountDue = 0,      // full amount of sale including tax
   netSales =0,   // net sale


   ifstream input("c:\\Lab3data.txt");      // read text file

   if (!input)  // incase of problems opening the file
   {
      cout << " Cant open the file.\n\n";
      // use return.  Don't use exit() in C++.
      return -1;
   }//end if


   // These figures only occur at the very start, right?
   input >> store >> taxrate;

   cout << "\n _______________________________________________________________";
   cout << "\n\n Store: "<< store << "\n\n";

   while (true)
   {
      int    customernumber;  // customer number.
      string customername;    // customer name
      int    salecount;       // number of sales.
      string credit;          //credit card number

      input >> customernumber >> customername >> salecount >> credit;

      if (customernumber == -1)  // if the file is done, then
         break;                  // Abort the loop.

      cout << " Credit Card Number: " << credit << endl;
      cout << " Customer Name: "      << customer <<"\n\n";

      cout << " Item" << setw(16)
           << "Quantity" << setw(16)
           << "Unit Price"<< setw(22)
           << "Extended Price " << "\n " ;

      for (int i = 0; i < salecount; ++i)
      {
         int    item;          // item number
         int    recordnumber;
         int    qty;           // quantity of items
         float  unitPrice;     // price of the unit
         string TaxFlg;

         input >> item >> qty >> price >> TaxFlg;

         cout << setiosflags( ios::showpoint | ios::fixed)
              << setprecision(2)<< item << setw(8)<< qty
              << setw(17) << unitPrice << setw(17)
              << extendedPrice[6] << setw(10);
         if (TaxFlg[0] == 'Y')
            cout << "TAXABLE\n\n";   //indicate that item is taxable
         else
            cout << "NON-TAXABLE\n\n";   //indicates that item is non-taxable

         float SaleAmount = unitPrice*Qty;
         float SaleTax    = SaleAmount*Tax/100;
         float SaleTotal  = SaleAmount+SaleTax;

         netSales  += SaleAmount;
         TotalTax  += SaleTax;
         amountDue += SaleTotal;
      }

   }
// I think your tax formula was off.
//                   //netSales = (unitPrice) * (qty);
//                   //totalTax = (tax) * (100);
//                   //amountDue = netSales + totalTax;

   cout << setw(30) << "Net SALES " << setw(15) << netSales << endl;
   cout << setw(24) << "Tax " << "%" << setw(20) << totalTax <<endl;
   cout << setw(39) << "Amount Due " << setw(6) << amountDue << endl;

   cout << "\n _______________________________________________________________";

   return 0;
}
0
 

Author Comment

by:katdude
ID: 2607239
nietod;

I ran the code, but it isnt working. It might be my compiler, (Borland C++ 5.02),  

I was getting some error messages. I was able to get rid of all but one. It says, "illeagal structure operation". it is pointing towards this area,    
     input >> store >> taxrate;


I am trying to figure this out, but nothing is working for me....
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 22

Expert Comment

by:nietod
ID: 2607562
I compiled the code and fixed a few small errors--typos really. I'm not sure about that error you were getting??  This code compiled and works.  The ouput comes out correctly but is poorly formatted, you need to fool with the column widths a little.




#include<stdlib.h>
#include<fstream>
#include<iomanip>
#include<iostream>
#include<math.h>
#include<string>

using namespace std;

int main()
{
   string invoice;
   // This should have been "char store[4]", not "int store[4]"
   // but an int work even better.
   int    store;           // store number
   float  taxrate;         // tax rate.
   int    totalTax=0;      // total tax
   int    amountDue=0;     // full amount of sale including tax
   int    netSales =0;     // net sale


   ifstream input("d:\\tstcon\\Lab3data.txt");      // read text file

   if (!input)  // incase of problems opening the file
   {
      cout << " Cant open the file.\n\n";
      // use return.  Don't use exit() in C++.
      return -1;
   }//end if


   // These figures only occur at the very start, right?
   input >> store >> taxrate;

   cout << "\n _______________________________________________________________";
   cout << "\n\n Store: "<< store << "\n\n";

   while (true)
   {
      int    customernumber;  // customer number.
      string customername;    // customer name
      int    salecount;       // number of sales.
      string credit;          //credit card number

      input >> customernumber >> customername >> salecount >> credit;

      if (customernumber == -1)  // if the file is done, then
         break;                  // Abort the loop.

      cout << " Credit Card Number: " << credit << endl;
      cout << " Customer Name: "      << customername << endl << endl;

      cout << " Item" << setw(16)
           << "Quantity" << setw(16)
           << "Unit Price"<< setw(22)
           << "Extended Price " << endl;

      for (int i = 0; i < salecount; ++i)
      {
         int    item;          // item number
         int    qty;           // quantity of items
         float  unitPrice;     // price of the unit
         string TaxFlg;

         input >> item >> qty >> unitPrice >> TaxFlg;

         float  extendedPrice = qty*unitPrice;
   

         cout << setiosflags( ios::showpoint | ios::fixed)
              << setprecision(2)<< item << setw(8)<< qty
              << setw(17) << unitPrice << setw(17)
              << extendedPrice << setw(10);
         if (TaxFlg[0] == 'Y')
            cout << "TAXABLE\n\n";   //indicate that item is taxable
         else
            cout << "NON-TAXABLE\n\n";   //indicates that item is non-taxable

         float SaleAmount = unitPrice*qty;
         float SaleTax    = SaleAmount*taxrate/100;
         float SaleTotal  = SaleAmount+SaleTax;

         netSales  += SaleAmount;
         totalTax  += SaleTax;
         amountDue += SaleTotal;
      }

   }
// I think your tax formula was off.
//                   //netSales = (unitPrice) * (qty);
//                   //totalTax = (tax) * (100);
//                   //amountDue = netSales + totalTax;

   cout << setw(30) << "Net SALES " << setw(15) << netSales << endl;
   cout << setw(24) << "Tax " << "%" << setw(20) << totalTax <<endl;
   cout << setw(39) << "Amount Due " << setw(6) << amountDue << endl;

   cout << "\n _______________________________________________________________";

   return 0;
}
0
 

Author Comment

by:katdude
ID: 2607899
Still doesnt work. I dont know what to do now.
0
 

Author Comment

by:katdude
ID: 2607919
Now I am getting these errors, i dont know how to fix them. do you know what they are?

1. undefined symbol std::rwseStringIndexOutOfRangeInModule

2. undefined symbol std::nullref in module

3. undefined symbol std::rwse_PosBeyondEndOfString in module

4. undefined symbol std::InvalidSizeParam in module

5. undefined symbol std::ResultLenInvalid in module

6. undefined symbol std::UnexpectedNullPtr in module

7. undefined symbol std::__rw_stdexcept_NoNamedException in module
0
 
LVL 22

Expert Comment

by:nietod
ID: 2607921
It works for me.  So there's probalby nothing major wrong.  Probably small problems due to compiler differences.  What compiler are you using?  (it compiled and ran fun under VC 6.) What errors are you getting?
0
 

Author Comment

by:katdude
ID: 2608050
Adjusted points to 350
0
 

Author Comment

by:katdude
ID: 2608051
this runs, but it only shows the first part of the line on the first customer invoice, and then it is stopping. I need it to finish all of the invoices for each customer. but it stops.

Also I think the code you sent, without the old headers (.h>) is giving me problems.

I havent ever used the headers without the .h> in them. I wonder if that is why the code you sent me isnt running on my compiler. when i run the EXE it beeps, and shows all kinds of wierd characters on the screen. at the end it only showws part of the invoice.
 

--------------------------------------------------------------------------------------
#include<iostream.h>
#include<fstream.h>
#include<iomanip.h>
#include<stdlib.h>

void outputline( int, const char *, int, const char *, int, long,
 int, int, float, char);


      int main()
      {      int store,                     // Store number
             cust_number,         // Customer number
             items_purchased,     // Number of items purchased
      item_number,         // Item catalog number
      qty,                 // Quantity of items
      netSales,            // Total Net Sales
      amt_due,             // Total amount due including tax
      extPrice,            // The extended price
      ext;                 // The value of the extended price

      float unitPrice;           // Unit price
      float extendedPrice;       // Total extended price = unitPrice * qty

         long credit_card;         // Credit card number
      char yes;
         char file_name;         // Name of the file that the user will enter
         char Tax_rate[30];      // TAX rate
         char custName[25];      // Customers last name
      char tMsg;
      int i = 0;

   cout << " Please enter a file name: ";
   cin >> file_name;       // Name of the file that the user will enter

   ifstream infile("a:\\Lab3data.txt", ios::in);    // read file from disk

            if (!infile)
               {cerr << " File not found! \n";
                     exit(-1);
            }  // end if

      while (infile >> store >> Tax_rate >> cust_number >> custName
      >> items_purchased >> credit_card >> item_number >> qty >> unitPrice)

         outputline(store, Tax_rate, cust_number, custName, items_purchased,
          credit_card, item_number, qty, unitPrice, tMsg); //call to function output line

      extendedPrice = qty * unitPrice; // calculates the extended price

      cout << setw(17) << setiosflags( ios::fixed |ios::showpoint)
      << setprecision(2)<< extendedPrice ;
            if (tMsg == 'Y')
                  {cout << "Taxable";}
            else
               cout << " \n\n" ;
         cout << "        ___________________________________________________\n\n\n";

   return 0; //
} // end main

//-----------------------function outputline------------------------------------
//this function reads in the file data, and formats it accordingly
//to it s category, then it sends back the information to main.

void outputline( int store_num, const char *tax_rate, int cust_num,
 const char *name, int num_items, long credit, int item, int qty,
  float unitPrice, char tMsg) // out put function
{       int i =0;

       for ( i = 0; i < 9; i++)

              {cout <<"\n      ___________________________________________________\n\n"
       <<"            MARK HADSELL's PRODUCE COMPANY\n\n" //title

             << " Store:     "<< setiosflags(ios::left) << setw(12) << store_num
       <<endl << endl         //read store number

       << " Tax Rate: "<< setiosflags(ios::left)<< setw(4) << tax_rate <<"%"
       << endl << endl        // read tax rate

       << " Customer#: "<< setiosflags(ios::left)<< setw(7)
       << cust_num << "\n\n"  // read customer nnumber

       << " CUSTOMER: " << setiosflags(ios::left) << setw(10)
       << name << endl << endl       // read customers last name

       << " Number of items " << setiosflags(ios::left) << setw(10)
       << num_items << endl << endl << setiosflags(ios::left) << setw(13)

       << " Credit Card #: " << setiosflags(ios::left) << setw(2)
       <<  credit << endl << "\n   "
       << " Items " << setiosflags(ios::left) << setw(16)
       << " Quantity "<< setiosflags(ios::left) << setw(16)
       << " Unit Price "<< setiosflags(ios::left) << setw(16)
       << " Extended Price " << endl << endl
       << resetiosflags(ios::left) << setw(8)
       << item
       << resetiosflags(ios::left) << setw(8)
       << qty
       << setw(18) << setiosflags(ios::fixed |ios::showpoint)
             << setprecision(2)<< unitPrice;
       }//end while
       i=i+1;
}
//----------------------end outputline function---------------------------------


I really do appreciate your help..

0
 

Author Comment

by:katdude
ID: 2608055
the compiler i have is Borland C++ 5.02
0
 
LVL 22

Expert Comment

by:nietod
ID: 2608168
>> I havent ever used the headers without the .h> in them.
>> I wonder if that is why the code you sent me isnt running
>> on my compiler.
Its possible, but not likely.  However it is easy enough to try.  add the .h back and remove the "using namespace std;"

>> when i run the EXE it beeps, and shows
>> all kinds of wierd characters on the screen. at the end it
>> only showws part of the invoice.
Wow. I can't image why.  When you debug do you see it read in the correct data and then print incorrect data?  Or is it reading in incorrect data?

>> the compiler i have is Borland C++ 5.02
That compiler is VERY old.  But still I can't believe that it would cause the behavior you describe.   All the same, you really need to upgrade.  I would recommend buying VC 6 or BCB 5.  BC 5 is so out-of-date that Borland is now offering it for free on the web.
0
 

Author Comment

by:katdude
ID: 2638559
Thank you for your help, I finnaly got it to run. I had to use some pointers and refferance some addresses to get it to run correctly.
0
 
LVL 22

Expert Comment

by:nietod
ID: 2639810
I'm not sure why....  Anyways, seriously consider upgrading, you'be be glad you did.  Student copies of BCB and VC are about $100 and worth every penny (I would recommend VC unless you are planning on doing windows programming in VCL)
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now