Adding Values read from a text file.

Write your question here.
I am writing a code to read from a text file and I need to add all the values of the retail_value together. How can I write that using a loop to add each price from the text file of the retail_price and list the total on the bottom? Do I use a loop to run through the file and add each value found in retail price?

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <cctype>

using namespace std;

//Prototype Statements

void displayOutput(string [], string [],string[], double [], int );
void getData(string , string [], string [], string [], double [] , int &);

const int MAX_INVENTORY = 500;

int main()
{
string filename = "motorsports inventory.txt";
int discount;

string model_number[MAX_INVENTORY], type[MAX_INVENTORY], description[MAX_INVENTORY];
double retail_price [MAX_INVENTORY];
int num_inventory = 0;

system("color f0");


getData(filename, model_number, type, description, retail_price, num_inventory);

displayOutput(model_number, type, description, retail_price, num_inventory);

}
void displayOutput(string model_number[], string type[], string description[], double retail_price[], int num_inventory)
{

cout << endl << endl << setprecision(2) << fixed;
for (int c = 0; c < num_inventory; c++)
{
cout << left << setw(5) << model_number[c]
<< " " << setw(15) << type[c]
<< right << setw(7) << description[c]
<< setw(25) << "$" << retail_price[c] << endl;
}


}
void getData(string filename, string model_number[], string type[], string description[], double retail_price[], int &num_inventory)
{
ifstream infile;
infile.open(filename.c_str());
if (infile.fail())
{
cout << "Error: Cannot open file. ";
return;
}
string line;

int c = 0;
while (getline(infile, model_number[c]))
{
getline(infile, type[c]);
getline(infile, description[c]);
infile >> retail_price[c];
infile.ignore();
getline(infile, line); //read blank line
c++;
}
infile.close();

num_inventory = c;
}
Hello lg77756,

While I work on your code.


PLEASE ALWAYS USE CODE TAGS (the <> formatting button), to the right of this box, when posting code.

Along with the proper indenting it makes it easier to read your code and also easier to respond to your post.

http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/

Hint: You can edit your post, highlight your code and press the <> formatting button. This will not automatically indent your code. That part is up to you.

You can use the preview button at the bottom to see how it looks.

I found the second link to be the most help.


And since the program reads an input file please post the input file or a good sample if it is large. If there is anything in the input file that is causing a problem make sure that is included.

Andy
add each price from the text file of the retail_price and list the total on the bottom


Consider (not tried as no file data provided) - I've 'tidied up' the code a little bit:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>

using namespace std;

//Prototype Statements

void displayOutput(string[], string[], string[], double[], size_t);
void getData(const string&, string[], string[], string[], double[], size_t&);

const size_t MAX_INVENTORY {500};

int main()
{
	const string filename {"motorsports inventory.txt"};
	string model_number[MAX_INVENTORY], type[MAX_INVENTORY], description[MAX_INVENTORY];
	double retail_price[MAX_INVENTORY] {};
	size_t num_inventory {MAX_INVENTORY};

	//system("color f0");

	getData(filename, model_number, type, description, retail_price, num_inventory);
	displayOutput(model_number, type, description, retail_price, num_inventory);

	double total_ret {};

	for (size_t r = 0; r < num_inventory; ++r)
		total_ret += retail_price[r];

	cout << "Total retial price is: " << total_ret << '\n';
}

void displayOutput(string model_number[], string type[], string description[], double retail_price[], size_t num_inventory)
{
	cout << "\n\n" << setprecision(2) << fixed;

	for (size_t c = 0; c < num_inventory; ++c) {
		cout << left << setw(5) << model_number[c]
			<< " " << setw(15) << type[c]
			<< right << setw(7) << description[c]
			<< setw(25) << "$" << retail_price[c] << '\n';
	}
}

void getData(const string& filename, string model_number[], string type[], string description[], double retail_price[], size_t& num_inventory)
{
	size_t maxinv {num_inventory};

	num_inventory = 0;

	ifstream infile (filename);

	if (!infile) {
		cout << "Error: Cannot open file. ";
		return;
	}

	for (string line; (num_inventory < maxinv) && getline(infile, model_number[num_inventory]); ++num_inventory) {
		getline(infile, type[num_inventory]);
		getline(infile, description[num_inventory]);
		infile >> retail_price[num_inventory] >> ws;
		getline(infile, line); //read blank line
	}
}

Last edited on
Hello lg77756,

Looking at your code there are several things that you could do differently.

If this is for school you need to post the instructions that you were given so everyone will know what you can and can not do or use.

"main" starts off by creating 4 arrays. 2 arrays is fine 3 or more tends to scream for a "struct" and 1 array of structs. If you have covered "vectors" a vector of structs would be better.

You have created the variable num_inventory in "main" and passed it by reference to the getData You also need a variable to hold the "total" that you would get in the "getData" function. This could also be passed by reference. Or returned by the function.

The following is your code restructured. Removed some extra blank lines and added some. See what you think. The comments in the code should help. Some of the code I did not change to give you some practice.

The 2 functions at the end you may find useful. These are better than "system" calls that you should avoid as they are not safe.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include <iostream>
#include <iomanip>
#include <string>
#include <cctype>
#include <Windows.h>
#undef min
#undef MAX

#include <fstream>

using namespace std;  // <--- Best not to use.

#define CLS cls();

//Prototype Statements
void displayOutput(string[], string[], string[], double[], int);
int getData(const string, string[], string[], string[], double[], int &, double& total);
void SetColor(short foreground, short background);
void cls();

const int MAX_INVENTORY = 500;

int main()
{
    const string filename = "motorsports inventory.txt";  // <--- Changed.
    int discount{}, responce{};
    double total{};

    string model_number[MAX_INVENTORY], type[MAX_INVENTORY], description[MAX_INVENTORY];
    double retail_price[MAX_INVENTORY]{};
    int num_inventory{};

    //system("color f0");
    SetColor(0, 15);

    CLS;

    if(responce=getData(filename, model_number, type, description, retail_price, num_inventory, total))
       return responce;

    displayOutput(model_number, type, description, retail_price, num_inventory);

}

void displayOutput(string model_number[], string type[], string description[], double retail_price[], int num_inventory)
{

    cout << endl << endl << setprecision(2) << fixed;

    for (int c = 0; c < num_inventory; c++)
    {
        cout << left << setw(5) << model_number[c]
            << " " << setw(15) << type[c]
            << right << setw(7) << description[c]
            << setw(25) << "$" << retail_price[c] << endl;
    }
}

int getData(const string filename, string model_number[], string type[], string description[], double retail_price[], int &num_inventory, double& total)
{
    ifstream infile;
    infile.open(filename);  // <--- From C++11 on the ".c_str()" is not needed.

    if (infile.fail())  // <--- if (!infile) will check for more than just the "fail" bit.
    {
        cerr << "\n     Error: Cannot open file. ";  // <--- Changed.

        return 1;
    }

    string line;

    int c = 0;  // <--- This is not needed. Just use "num_inventory".

    while (getline(infile, model_number[c]))
    {
        getline(infile, type[c]);

        getline(infile, description[c]);

        infile >> retail_price[c];

        total += retail_price[c];

        infile.ignore();

        getline(infile, line); //read blank line

        c++;
    }

    //infile.close();  // <--- Not required as the dtor will close the file when the function looses scope.

    num_inventory = c;  // <--- Not needed if you just use "num_inventory".

    return 0;
}

void SetColor(short foreground, short background)
{
    WORD consoleColor;
    HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO csbi;

    if (GetConsoleScreenBufferInfo(hStdOut, &csbi))
    {
        //consoleColor = (csbi.wAttributes & 0xF0) + (ColorPicker & 0x0F);
        consoleColor = (foreground + (background * 16));
        SetConsoleTextAttribute(hStdOut, consoleColor);
    }
}  //  End SetColor()

void cls()
{
    const HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
    DWORD dwMode;

    if (hOut != INVALID_HANDLE_VALUE)
        if (GetConsoleMode(hOut, &dwMode))
            if (SetConsoleMode(hOut, dwMode | ENABLE_VIRTUAL_TERMINAL_PROCESSING))
                printf("\x1b[H\x1b[2J");  // Home and clear screen
}

This is untested as you did not provide an input file to use.

Andy
Hello lg77756,

I realized there is 1 change I forgot to make.

For the prototype void SetColor(short foreground = 7, short background = 1);, so that you can use SetColor(); to use the default values.

The default colors you can change to whatever you want, but I have found these to be easier on the eyes to read especially in a room with less light.

Andy
My teacher wants me to have all of it displayed as this. He wants us to ask the user to enter a discount amount.
Inventory Number.   Type.      Description.                             Price.        Discou Price
            ATV-YA364               ATV        2020 YAMAHA GRIZZLY EPS.    $9899.00  ------------
......             ........         ......................................        .........     ..................
                                                                              
All Prices Totaled:         Discounts Totaled:


This is what the text file looks like.

ATV-YA364
ATV
2020 Yamaha Grizzly EPS
9899

JET-SD387
Jet Ski
2020 Sea-Doo RXP-X 300
13999

MTC-KI251
Motorcycle
2021 Kawasaki KX 250
8299

UTV-CA476
UTV
2021 Can-Am Maverick Trail DPS 1000
15199

ATV-HA450
ATV
2020 Honda Bear 4X4
5000

UTV-KI387
UTV
2021 Kawasaki Mule Pro-MX
10299

ATV-YA398
ATV
2021 Yamaha Grizzly EPS XT-R
10999

JET-KI365
Jet Ski
2021 Kawasaki Ultra 310LX
18199

JET-KI903
Jet Ski
2020 Kawasaki Jet Ski Ultra 310R
16299

ATV-HA387
ATV
2020 Honda FourTrax Rancher 4X4
6499

MTC-HA251
Motorcycle
2021 Honda CRF250R
7999

MTC-HA376
Motorcycle
2021 Honda CRF110F
2499

ATV-HA273
ATV
2021 Honda FourTrax Rancher 4X4 ES
6799

ATV-HA374
ATV
2021 Honda FourTrax Foreman 4X4
7399

MTC-YA121
Motorcycle
2021 Yamaha TT-R125LE
3349

UTV-CA605
UTV
2021 Can-Am Maverick X3 MAX DS Turbo
21999

ATV-CA247
ATV
2021 Can-Am Outlander 570
6999

MTC-YA458
Motorcycle
2021 Yamaha YZ450F
9399

ATV-CA647
ATV
2021 Can-Am Outlander DPS 570
7899

UTV-HA405
UTV
2021 Honda Pioneer 1000 Limited Edition
18999

UTV-HA476
UTV
2021 Honda Pioneer 1000
15899

JET-KI373
Jet Ski
2020 Kawasaki Jet Ski STX 160X
9999

ATV-YA335
ATV
2021 Yamaha Kodiak 700
7299

UTV-KI508
UTV
2021 Kawasaki Mule SX 4X4 XC Camo Fl
9199

ATV-KI373
ATV
2021 Kawasaki KFX90
2599

MTC-KI454
Motorcycle
2021 Kawasaki KX 450XC
9599


I apologize for not knowing much about this site! We just ended the array chapter of our textbook. And we are about to learn using linear search and binary search.
Last edited on
Hello lg77756,

I am still having a hard time understanding the discount part. Implementing the discount is easy in the "displayOutput" function, but my questions are:

Does the discount apply to every item in the file or just certain items?

You have implied that the discount is entered by the user, so should there be a limit not to exceed or is anything possible?

I am guessing that the discount is entered as a whole number?

As a start I did this with the "displayOutput" function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void displayOutput
(const string model_number[], const string type[], const string description[], const double retail_price[],
 const int num_inventory, const double total)
{

    cout << setprecision(2) << fixed;

    std::cout <<
        " Modle#       Type                 Description                      Price\n"
        << ' ' << std::string(75, '-') << '\n';

    for (int c = 0; c < num_inventory; c++)
    {
        cout << ' ' << left << setw(11) << model_number[c]
            << " " << setw(12) << type[c]
            << setw(40) << description[c] << '$'
            << right << setw(10) << retail_price[c] << '\n';
    }

    std::cout
        << ' ' << std::string(75, '=') << '\n'
        << " Total" << std::string(59, ' ') << '$' << std::setw(10) << total << '\n';
}


And it produces this output:

 Modle#       Type                 Description                      Price
 ---------------------------------------------------------------------------
 ATV-YA364   ATV         2020 Yamaha Grizzly EPS                 $   9899.00
 JET-SD387   Jet Ski     2020 Sea-Doo RXP-X 300                  $  13999.00
 MTC-KI251   Motorcycle  2021 Kawasaki KX 250                    $   8299.00
 UTV-CA476   UTV         2021 Can-Am Maverick Trail DPS 1000     $  15199.00
 ATV-HA450   ATV         2020 Honda Bear 4X4                     $   5000.00
 UTV-KI387   UTV         2021 Kawasaki Mule Pro-MX               $  10299.00
 ATV-YA398   ATV         2021 Yamaha Grizzly EPS XT-R            $  10999.00
 JET-KI365   Jet Ski     2021 Kawasaki Ultra 310LX               $  18199.00
 JET-KI903   Jet Ski     2020 Kawasaki Jet Ski Ultra 310R        $  16299.00
 ATV-HA387   ATV         2020 Honda FourTrax Rancher 4X4         $   6499.00
 MTC-HA251   Motorcycle  2021 Honda CRF250R                      $   7999.00
 MTC-HA376   Motorcycle  2021 Honda CRF110F                      $   2499.00
 ATV-HA273   ATV         2021 Honda FourTrax Rancher 4X4 ES      $   6799.00
 ATV-HA374   ATV         2021 Honda FourTrax Foreman 4X4         $   7399.00
 MTC-YA121   Motorcycle  2021 Yamaha TT-R125LE                   $   3349.00
 UTV-CA605   UTV         2021 Can-Am Maverick X3 MAX DS Turbo    $  21999.00
 ATV-CA247   ATV         2021 Can-Am Outlander 570               $   6999.00
 MTC-YA458   Motorcycle  2021 Yamaha YZ450F                      $   9399.00
 ATV-CA647   ATV         2021 Can-Am Outlander DPS 570           $   7899.00
 UTV-HA405   UTV         2021 Honda Pioneer 1000 Limited Edition $  18999.00
 UTV-HA476   UTV         2021 Honda Pioneer 1000                 $  15899.00
 JET-KI373   Jet Ski     2020 Kawasaki Jet Ski STX 160X          $   9999.00
 ATV-YA335   ATV         2021 Yamaha Kodiak 700                  $   7299.00
 UTV-KI508   UTV         2021 Kawasaki Mule SX 4X4 XC Camo Fl    $   9199.00
 ATV-KI373   ATV         2021 Kawasaki KFX90                     $   2599.00
 MTC-KI454   Motorcycle  2021 Kawasaki KX 450XC                  $   9599.00
 ===========================================================================
 Total                                                           $ 262625.00


I think it looks better, but you can change it or setup the output any way that you like.

What I do want you to see is how I used the "setw()"s to add space between the fields. If yo do not understand let me know.

Either way you can code in "main" B4 the "displayOutput" function or write a separate function to get the information about the discount.

Andy
Hello lg77756,

I am not sure if this is what you are after, so let me know if I have anything wrong. I have moved some thing around and cut it down for testing.

 Enter a discount amount: 10



 Enter a discount amount: 10
                                                                                Discount
 Modle#       Type                 Description                      Price        Price
 ----------------------------------------------------------------------------------------
 ATV-YA364   ATV         2020 Yamaha Grizzly EPS                 $   9899.00  $   8909.10
 JET-SD387   Jet Ski     2020 Sea-Doo RXP-X 300                  $  13999.00  $  12599.10
 MTC-KI251   Motorcycle  2021 Kawasaki KX 250                    $   8299.00  $   7469.10
 UTV-CA476   UTV         2021 Can-Am Maverick Trail DPS 1000     $  15199.00  $  13679.10
 ATV-HA450   ATV         2020 Honda Bear 4X4                     $   5000.00  $   4500.00
 ========================================================================================
 Totals                                                          $  52396.00  $  47156.40



Andy
That is exactly what I am looking for. I am just trying to understand how to go about it.
Last edited on
Hello lg77756,

Instead of a long explanation this is what I ended up with:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
void displayOutput
(const string model_number[], const string type[], const string description[], const double retail_price[],
 const int num_inventory, const double DISCOUNT)
{
    double discountTotal{};
    double total{};

    cout << setprecision(2) << fixed;

    CLS;

    std::cout <<
        std::string(80, ' ') << "Discount\n"
        " Modle#       Type                 Description                      Price        Price\n"
        << ' ' << std::string(88, '-') << '\n';

    for (int idx = 0; idx < 5/*num_inventory*/; idx++)
    {
        cout << ' ' << left << setw(11) << model_number[idx]
            << " " << setw(12) << type[idx]
            << setw(40) << description[idx] << '$'
            << right << setw(10) << retail_price[idx]
            << "  $" << std::setw(10) << retail_price[idx] - (retail_price[idx] * DISCOUNT / 100.0) << '\n';

        total += retail_price[idx];

        discountTotal += retail_price[idx] - (retail_price[idx] * DISCOUNT / 100.0);
    }

    std::cout
        << ' ' << std::string(88, '=') << '\n'
        << " Totals" << std::string(58, ' ') << '$' << std::setw(10) << total
        << "  $" << std::setw(10) << discountTotal << '\n';
}

I thought of another option. Create a 3rd variable in the function for the discount amount and add a new column to the for loop for the amount of the discount. Then changing what precedes the for loop, the for loop and what fillows the for loop would be easy to change.

I think I will give the new column a shot and see what I come up with.

Andy
Registered users can post here. Sign in or register to post.