Do-While Loop help!

Hi everyone!

So new to this, I might have started my assignment wrong. I'm not sure, basically i'm suppose to list 5 cars with different mpg's and suppose to ask a user to pick TWO of them. Which I already have the cars listed, NOW im suppose to start a Do-While loop where I need to ask user for how many miles they intend to drive and the price of gas. Then do calculations of how much gallons will be needed to be driven for the year and the cost of the year. Then report to the user each vehicle with how much gallons needed and the cost. And if the user enters a choice of <1 or >5 tell them invalid and ask if theyd like to enter a option again. I'm at a stop, I need a little help just a push on how to continue or ask the user to enter two vehicles.

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
#include <iostream>
#include <vector>
#include <string> 


using namespace std;
int main()


{


	//Declare vectors
	vector<string> vehicles; 
	vector<double> mpg;

	//Vectors with vehicle names
	vehicles.push_back("Ford Fusion");
	vehicles.push_back("Honda Fit");
	vehicles.push_back("Jeep Renegade");
	vehicles.push_back("Chrysler 300");
	vehicles.push_back("Ram");

	//Vectors with mpg
	mpg.push_back(21);
	mpg.push_back(28);
	mpg.push_back(22);
	mpg.push_back(19);
	mpg.push_back(16);

	//List vehicles with mpg
	do

	{
		cout << "Vehicle 1 is a " << vehicles.at(0) << " with an mpg of " << mpg.at(0) << endl;
		cout << "Vehicle 2 is a " << vehicles.at(1) << " with an mpg of " << mpg.at(1) << endl;
		cout << "Vehicle 3 is a " << vehicles.at(2) << " with an mpg of " << mpg.at(2) << endl;
		cout << "Vehicle 4 is a " << vehicles.at(3) << " with an mpg of " << mpg.at(3) << endl;
		cout << "Vehicle 5 is a " << vehicles.at(4) << " with an mpg of " << mpg.at(4) << endl;
		
	}

	

	return 0;
}
Last edited on
It might be easier to process if you have a vector of struct, rather than using 2 vectors. For a possible starter to display and get 2 vehicles, consider C++20:

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
#include <iostream>
#include <vector>
#include <string>
#include <limits>

using namespace std;

struct Car {
	string name;
	double mpg {};
};

int main()
{
	const vector<Car> vehicles {{"Ford Fusion", 21}, {"Honda Fit", 28}, {"Jeep Renegade", 22}, {"Chrysler 300", 19}, {"Ram", 16}};

	for (size_t vehno {}; const auto& [vehnam, vmpg] : vehicles)
		cout << "Vehicle " << ++vehno << " is a " << vehnam << " with an mpg of " << vmpg << '\n';

	cout << '\n';

	for (size_t choice {1}; choice <= 2; ++choice) {
		size_t veh {};

		while ((cout << "Choice " << choice << ". Enter a car number (1 - " << vehicles.size() << ") : ") && (!(cin >> veh) || veh < 1 || veh > vehicles.size()))
			if (!cin) {
				cout << "Invalid number\n";
				cin.clear();
				cin.ignore(numeric_limits<streamsize>::max(), '\n');
			} else
				cout << "Number out of range\n";

		// Process chosen vehicle here
		--veh;
		cout << "Vehicle " << choice << ". " << vehicles[veh].name << "  " << vehicles[veh].mpg << '\n';
	}
}



Vehicle 1 is a Ford Fusion with an mpg of 21
Vehicle 2 is a Honda Fit with an mpg of 28
Vehicle 3 is a Jeep Renegade with an mpg of 22
Vehicle 4 is a Chrysler 300 with an mpg of 19
Vehicle 5 is a Ram with an mpg of 16

Choice 1. Enter a car number (1 - 5) : 2
Vehicle choice 1. Honda Fit  28
Choice 2. Enter a car number (1 - 5) : q
Invalid number
Choice 2. Enter a car number (1 - 5) : 6
Number out of range
Choice 2. Enter a car number (1 - 5) : 5
Vehicle choice 2. Ram  16

Last edited on
ohhh, okay! Thank you! It's cause my assignment is asking for a vector of strings for vehicles and a vector of doubles for mpg
Hello miguelminaj,

While I look at your code you could post the instructions that you were given for this assignment.

It would also help if you mention what operating system you are using along with the IDE and compiler.

I did notice that line 32 starts a "do "loop, but there is no "while" to finish it.

Andy
Hi Andy,

And yes I didn't finish it with the while because i'm pretty lost. I keep doing re-search, watching videos and reading my books but I'm at a stop. Especially with more assignments from different classes. But the instructions are, I need a push or just a explanation of how I can continue it. The post above does help but I just forgot to include the instructions.

"Your program should do the following:
In Main, create and initialize the following vectors with information for five vehicles:
• Vector of strings with the names of the vehicles.
• Vector of doubles with the mpg for each vehicle.

Open a do-while loop so the user can play multiple times.

Display a nicely formatted list of the five types of cars and their expected mpg:
Option Vehicle MPG
1 Mitsubishi Mirage 34

Ask the user to “Select vehicle one:” and “Select vehicle two:”
Ask the user for the following information:
• How many miles they anticipate driving per year.
• Estimated cost of gasoline per gallon.

For each vehicle, calculate the gallons of fuel needed to drive miles driven per year and the cost of fuel needed for that vehicle.

Report the following back to the user:
• For each vehicle: The vehicle, the yearly total number of gallons and the yearly cost of fuel.
• Difference in cost between the two vehicles.

If the user entered a choice of <1 or >5, tell them that they entered an invalid option.
Ask the user if they want to run the program again. Be sure to tell the user the choices to enter. If the user says yes, loop back up to the top of the do-while loop. If no, drop out of the loop and write a good-bye message."
Hello miguelminaj,

It looks like the do/while loop is more to keep the program running for multiple uses. Once inside the loop you will need to print out the list of vehicles Then choose 2 from the list and after asking for the miles and gas price calculate the yearly cost.

After displaying the results ask the user if to continue with another choice or exit. Then the while condition will determine if to continue looping or exit the loop.

This is not a complete program, but you may find it helpful:
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
#include <iostream>
#include <iomanip>  // <--- Added.
#include <string> 
#include <vector>

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

int main()
{
    constexpr unsigned int WIDTH{ 13 };
    //Declare vectors

    //Vectors with vehicle names
    const vector<string> vehicles
    {
        "Ford Fusion",
        "Honda Fit",
        "Jeep Renegade",
        "Chrysler 300",
        "Ram"
    };

    //Vectors with mpg
    const vector<double> mpg{ 21.0, 28.0, 22.0, 19.0, 16.0 };

    std::cout << std::fixed << std::setprecision(2);  // <--- Only needs done once.

    //List vehicles with mpg
 
    cout 
        << std::left
        << "Vehicle 1 is a " << std::setw(WIDTH) << vehicles.at(0) << " with an mpg of " << mpg.at(0) << '\n'
        << "Vehicle 2 is a " << std::setw(WIDTH) << vehicles.at(1) << " with an mpg of " << mpg.at(1) << '\n'
        << "Vehicle 3 is a " << std::setw(WIDTH) << vehicles.at(2) << " with an mpg of " << mpg.at(2) << '\n'
        << "Vehicle 4 is a " << std::setw(WIDTH) << vehicles.at(3) << " with an mpg of " << mpg.at(3) << '\n'
        << "Vehicle 5 is a " << std::setw(WIDTH) << vehicles.at(4) << " with an mpg of " << mpg.at(4) << '\n';

    // <--- To Do
    //do
    //{

    //} while (true);  // <--- Condition needs changed.

    return 0;  // <--- Not required, but makes a good break point.
}

This is good for a start B4 it is all finished.

I do have 1 question. Have you studied functions yet?

Andy
Hello miguelminaj,

With some changes an additions I am up to this for now:
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
#include <iostream>
#include <iomanip>  // <--- Added.
#include <string> 
#include <vector>
#include <cctype>   // <--- Added.

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

int main()
{
    constexpr int WIDTH{ 13 };

    char playAgain{};
    double milesPerYear{}, priceOfGas{};

    //Declare vectors
    //Vectors with vehicle names
    const vector<string> vehicles
    {
        "Ford Fusion",
        "Honda Fit",
        "Jeep Renegade",
        "Chrysler 300",
        "Ram"
    };

    //Vectors with mpg
    const vector<double> mpg{ 21.0, 28.0, 22.0, 19.0, 16.0 };

    std::cout << std::fixed << std::setprecision(2);  // <--- Only needs done once.

    //List vehicles with mpg

    do
    {
        cout 
            << std::left
            << "Vehicle 1 is a " << std::setw(WIDTH) << vehicles.at(0) << " with an mpg of " << mpg.at(0) << '\n'
            << "Vehicle 2 is a " << std::setw(WIDTH) << vehicles.at(1) << " with an mpg of " << mpg.at(1) << '\n'
            << "Vehicle 3 is a " << std::setw(WIDTH) << vehicles.at(2) << " with an mpg of " << mpg.at(2) << '\n'
            << "Vehicle 4 is a " << std::setw(WIDTH) << vehicles.at(3) << " with an mpg of " << mpg.at(3) << '\n'
            << "Vehicle 5 is a " << std::setw(WIDTH) << vehicles.at(4) << " with an mpg of " << mpg.at(4) << '\n';

        //Ask the user to “Select vehicle one : ” and “Select vehicle two : ”
        //Ask the user for the following information :
        //• How many miles they anticipate driving per year.
        //• Estimated cost of gasoline per gallon.

        //For each vehicle, calculate the gallons of fuel needed to drive miles driven per year and the cost
        //of fuel needed for that vehicle.

        //Report the following back to the user :
        //• For each vehicle : The vehicle, the yearly total number of gallons and the yearly cost of fuel.
        //• Difference in cost between the two vehicles.




        std::cout << "\n Try another combination (Y/N): ";
        std::cin >> playAgain;

    } while (std::toupper(playAgain) == 'Y');  // <--- Condition needs changed.

    return 0;  // <--- Not required, but makes a good break point.
}

You will need some more variables and the commented section is what you need to finish.

Andy
It's cause my assignment is asking for a vector of strings for vehicles and a vector of doubles for mpg


OK. Try this for a starter:

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
#include <iostream>
#include <vector>
#include <string>
#include <limits>
#include <cctype>

using namespace std;

int main()
{
	const vector<string> vehname {"Ford Fusion", "Honda Fit", "Jeep Renegade", "Chrysler 300", "Ram"};
	const vector<double> vehmpg {21.0, 28.0, 22.0, 19.0, 16.0};

	static_assert(sizeof(vehname) == sizeof(vehmpg));

	char playAgain {};

	do {

		for (size_t vehno {}; vehno < vehname.size(); ++vehno)
			cout << "Vehicle " << vehno + 1 << " is a " << vehname[vehno] << " with an mpg of " << vehmpg[vehno] << '\n';

		cout << '\n';

		for (size_t choice {1}; choice <= 2; ++choice) {
			size_t veh {};

			while ((cout << "Choice " << choice << ". Enter a car number (1 - " << vehname.size() << ") : ") && (!(cin >> veh) || veh < 1 || veh > vehname.size()))
				if (!cin) {
					cout << "Invalid number\n";
					cin.clear();
					cin.ignore(numeric_limits<streamsize>::max(), '\n');
				} else
					cout << "Number out of range\n";

				--veh;
				cout << "Vehicle " << choice << ". " << vehname[veh] << "  " << vehmpg[veh] << '\n';

				double miles {}, cpg {};

				cout << "How many miles do you anticipate driving per year: ";
				cin >> miles;

				cout << "Estimated cost of gasoline per gallon: ";
				cin >> cpg;

				// Perform calculations and display result here
		}

		std::cout << "Try another combination (Y/N): ";
		std::cin >> playAgain;

	} while (std::toupper(playAgain) == 'Y');

	cout << "Bye....\n";
}

Last edited on
Thank you guys so much for your help! Sadly I'm still stuck on the code and I had another question. I might have butchered my code completely but for the part on "Ask the user for vehicle option 1 & 2". How would I ask? Because I did the if-else statements. For example,


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
 //Ask the user to “Select vehicle one : ” and “Select vehicle two : ”
        cout << "Please enter your first vehicle choice. (1-5): ";
        int choice;
        cin >> choice;


        if (choice == 1)
        {
            cout << "Vehicle 1 is: " << vehicles.at(0) << endl;
        }

        else if (choice == 2)
        {
            cout << "Vehicle 2 is: " << vehicles.at(1) << endl;
        }

        else if (choice == 3)
        {
            cout << "Vehicle 3 is: " << vehicles.at(2) << endl;
        }

        else if (choice == 4)
        {
            cout << "Vehicle 4 is: " << vehicles.at(3) << endl;
        }

        else if (choice == 5)
        {
            cout << "Vehicle 5 is: " << vehicles.at(4) << endl;
        }
        else 
        {
            cout << "Out of Range!!!" << endl;
            
        }
Last edited on
Hello miguelminaj,

Nicely overdone. You need to make the code work for you not work against it.
Sometime you can use a variable over, but you have to be careful that you do not overwrite the variable B4 you have used it.

The user has to make 2 choices that tends to suggest that 2 variables are needed.

Instead of writing 2 sets of if/else if statements you already have what you need as the following code shows. Since the vector already exists you just need to access the correct element. The (- 1) is because the menu choice is 1 greater than the way the vector is numbered, which starts at (0)zero.

1
2
3
4
5
6
7
8
9
10
11
int vec1Choice{}, vec2Choice{};

//Ask the user to “Select vehicle one : ” and “Select vehicle two : ”
std::cout << "Please enter your first vehicle choice. (1-5): ";
std::cin >> vec1Choice;

std::cout << "Please enter your second vehicle choice. (1-5): ";
std::cin >> vec2Choice;

std::cout << "\n Vehicle 1 is: " << vehicles.at(vec1Choice - 1) << '\n';
std::cout << " Vehicle 1 is: " << vehicles.at(vec2Choice - 1) << '\n';

I am accepting that the menu has already been displayed B4 this code.

I have changed this code, but have not had a chance to test it yet.

Andy
Hi Andy, Thank you so much!! You are absolutely right! I removed my code, used yours and it worked so much better! I can understand yours clearly! I am almost done with my code. I have done everything, I am now only missing if input is <1 or >5 it is out of range! And ask if they want to run again. I just don't know how to write it. This is what I have now.

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
#include <iostream>
#include <iomanip>
#include <string> 
#include <vector>
#include <cctype>  
#include <cstdlib>

using namespace std;
int main()

{
	

	 constexpr int WIDTH{ 13 };

    char playAgain{};
    double milesPerYear{}, priceOfGas{};

    //Declare vectors
    //Vectors with vehicle names
    const vector<string> vehicles
    {
        "Ford Fusion",
        "Honda Fit",
        "Jeep Renegade",
        "Chrysler 300",
        "Ram"
    };

    //Vectors with mpg
    const vector<double> mpg{ 21.0, 28.0, 22.0, 19.0, 16.0 };

    std::cout << std::fixed << std::setprecision(2);

    //List vehicles with mpg

    do
    {
        cout
            << std::left
            << "Vehicle 1 is a " << std::setw(WIDTH) << vehicles.at(0) << " with an mpg of " << mpg.at(0) << '\n'
            << "Vehicle 2 is a " << std::setw(WIDTH) << vehicles.at(1) << " with an mpg of " << mpg.at(1) << '\n'
            << "Vehicle 3 is a " << std::setw(WIDTH) << vehicles.at(2) << " with an mpg of " << mpg.at(2) << '\n'
            << "Vehicle 4 is a " << std::setw(WIDTH) << vehicles.at(3) << " with an mpg of " << mpg.at(3) << '\n'
            << "Vehicle 5 is a " << std::setw(WIDTH) << vehicles.at(4) << " with an mpg of " << mpg.at(4) << '\n' << endl;

        //Ask the user to “Select vehicle one : ” and “Select vehicle two : ”
        int vec1Choice{}, vec2Choice{};

        //Ask the user to “Select vehicle one : ” and “Select vehicle two : ”
        std::cout << "Please enter your first vehicle choice. (1-5): ";
        std::cin >> vec1Choice;
        std::cout << "Please enter your second vehicle choice. (1-5): ";
        std::cin >> vec2Choice;

        //Show the user their vehicle choices
        std::cout << "\nVehicle 1 is: " << vehicles.at(vec1Choice - 1) << '\n';
        std::cout << "Vehicle 2 is: " << vehicles.at(vec2Choice - 1) << '\n' << endl;
        
        //Ask the user how much miles they plan on driving per year
        cout << "How much miles do you anticipate on driving per year?: ";
        cin >> milesPerYear;
       
        //Ask user the price of gas
        cout << "What's the price of gas?: ";
        cin >> priceOfGas; 
            
        //Calculations for vehicle 1
        //Gallons of fuel for vehicle one
        float gallonsPerYear; 
        gallonsPerYear = milesPerYear / mpg.at(vec1Choice - 1);
        cout << "Gallons per year for vehicle 1 is: " << gallonsPerYear << endl;

        //Cost of fuel for first vehicle
        float costOfFuel;
        costOfFuel = gallonsPerYear * priceOfGas;
        cout << "Cost of yearly fuel for vehicle 1 is: $" << costOfFuel << endl;
        
        //Calculations for vehicle 2
        //Gallons of fuel  for vehicle 2
        float gallonsForSecond;
        gallonsForSecond = milesPerYear / mpg.at(vec2Choice - 1);
        cout << "\nGallons per year for vehicle 2 is: " << gallonsForSecond << endl;

        //Cost of fuel for second vehicle
        float costOfFuelSecond;
        costOfFuelSecond = gallonsForSecond * priceOfGas;
        cout << "Cost of yearly fuel for vehicle 2 is: $" << costOfFuelSecond << endl;

        //Difference in cost of both vehicles
        float differenceCost;
        differenceCost = abs(costOfFuel - costOfFuelSecond); 
        cout << "Difference in cost of both vehicles is: $" << differenceCost; 



        std::cout << "\nTry another combination (Y/N): ";
        std::cin >> playAgain;
        cout << "Goodbye!" << endl;

    } while (std::toupper(playAgain) == 'Y');

    return 0;
}
Rather than have separate code for vehicle 1 and vehicle 2, this could be done using arrays and loops so that the code is only written once. What if you had to choose say 6 cars from 20?

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
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <cctype>
#include <cstdlib>

using namespace std;

int getInt(const std::string& prm, int minv, int maxv)
{
	do {
		std::cout << prm << " (" << minv << " - " << maxv << "): ";
		int i {};

		if ((std::cin >> i) && (i >= minv) && (i <= maxv) && std::cin.peek() == '\n') {
			std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
			return i;
		}

		if (!std::cin || std::cin.peek() != '\n')
			std::cout << "Not an integer\n";
		else
			std::cout << "Input not in range\n";

		std::cin.clear();
		std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	} while (true);
}

int getDouble(const std::string& prm)
{
	double i {};

	while ((std::cout << prm) && (!(std::cin >> i) || std::cin.peek() != '\n')) {
		std::cout << "Not a number\n";
		std::cin.clear();
		std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	}

	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	return i;
}

int main()
{
	constexpr int WIDTH {13};

	char playAgain {};

	const vector<string> vehicles { "Ford Fusion", "Honda Fit", "Jeep Renegade", "Chrysler 300", "Ram" };
	const vector<double> mpg {21.0, 28.0, 22.0, 19.0, 16.0};

	std::cout << std::fixed << std::setprecision(2);

	do {
		for (size_t v = 0; v < vehicles.size(); ++v)
			cout << left << "Vehicle " << v + 1 << " is a " << std::setw(WIDTH) << vehicles[v] << " with an mpg of " << mpg[v] << '\n';

		cout << '\n';

		int vecChoice[2] {};

		//Obtain vehicle choices
		for (size_t v = 0; v < 2; ++v) {
			const string prm {"Please enter choice for vehicle " + to_string(v + 1) + "."};

			vecChoice[v] = getInt(prm, 1, 5);
		}

		//Show the user their vehicle choices
		for (size_t v = 0; v < 2; ++v)
			std::cout << "\nVehicle " << v + 1 << " is: " << vehicles[vecChoice[v] - 1];

		double costOfFuel[2] {};

		//Ask the user how much miles they plan on driving per year
		cout << "\n\n";
		const auto milesPerYear {getDouble("How much miles do you anticipate on driving per year?: ")};

		//Ask user the price of gas
		const auto priceOfGas {getDouble("What's the price of gas?: ")};

		for (size_t v = 0; v < 2; ++v) {
			const auto gallons {milesPerYear / mpg[vecChoice[v] - 1]};
			cout << "\nGallons per year for vehicle " << v + 1 << " is: " << gallons << '\n';

			costOfFuel[v] = gallons * priceOfGas;
			cout << "Cost of yearly fuel for vehicle " << v + 1 << " is: $" << costOfFuel[v] << '\n';
		}

		//Difference in cost of both vehicles
		cout << "\nDifference in cost of both vehicles is: $" << abs(costOfFuel[0] - costOfFuel[1]) << '\n';

		std::cout << "\nTry another combination (Y/N): ";
		std::cin >> playAgain;

	} while (std::toupper(playAgain) == 'Y');

	cout << "\nGoodbye!" << endl;
}

Hello miguelminaj,

I have been going over your latest code and I do have some suggestions.

To start with you have written this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <iomanip>
#include <string> 
#include <vector>
#include <cctype>  
#include <cstdlib>

using namespace std;
int main()

{


    constexpr int WIDTH{ 13 };

The blank lines are good, but to many of them does not help. Consider this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <iomanip>
//#include <limits>  // <--- Not needed yet, but will have a futute use.
#include <string> 
#include <vector>
#include <cctype>  
#include <cstdlib>

using namespace std;

int main()
{
    constexpr int WIDTH{ 13 };

    char playAgain{};
    double milesPerYear{}, priceOfGas{};

I find this much easier to read. The first code makes me think that something is missing or should be added.

I realize that error checking may not have been covered yet, but there is no time like the present to learn.
1
2
3
4
5
6
7
8
9
10
const vector<double> mpg{ 0.0, 21.0, 28.0, 22.0, 19.0, 16.0 };

if (vehicles.size() != mpg.size())
{
    std::cerr << "\n     Vehicles contain : " << vehicles.size() << " items and mpgs contain: " << mpg.size() << " items.\n";

    std::cerr << "\n     Vehicle names do not match the mpgs!\n\n";

    return 1;
}

If you do not understand this let me know.

I will just mention this for now. The "cout" statement that prints the menu is fine and I just revised what you originally started with to show you a better way, but in the end a for loop would work better than all those individual lines. I will show you later.

The program is good down to:
1
2
3
4
5
6
7
//Calculations for vehicle 1
//Gallons of fuel for vehicle one

float gallonsPerYear;

gallonsPerYear = milesPerYear / mpg.at(vec1Choice - 1);
cout << "Gallons per year for vehicle 1 is: " << gallonsPerYear << endl;

The problem I see here is that both variables on the rhs of = are defined as "double"s, so after the calculation you are trying to but a larger "double" into a smaller "float". There will be data loss and I have seen where the last decimal number of a 'float" be rounded up B4 it chops of the extra digits.

Running all those lines together makes it hard to see the variable definition.

Unless you have a good reason the preferred floating point type is a "double". It is best to make all your variables match. Defining your variables as "float"s should produce a warning of possible data loss. This will not keep the program from running, but the result may not be what you expected.

What you have done after this point appears to be correct, although I have not completely checked the calculations.

The last line of the do/while loop is: cout << "\n\n Goodbye!\n\n";. I changed that a little. See what you think, but this line should be after the do/while loop just B4 the program ends.

Now here is a little trick you can use to make the code easier to write and use.

1
2
3
4
5
6
7
8
9
10
11
12
13
    //Vectors with vehicle names
    const vector<string> vehicles
    {
        "",
        "Ford Fusion",
        "Honda Fit",
        "Jeep Renegade",
        "Chrysler 300",
        "Ram"
    };

    //Vectors with mpg
    const vector<double> mpg{ 0.0, 21.0, 28.0, 22.0, 19.0, 16.0 };

Notice line 4 in "vehicles" This is just a place holder to give element (0) something. And in the "mps" vector I used (0.0).

Now you can change the first "cout" in the do/while loop to:
1
2
3
4
5
6
7
8
std::cout << std::left << '\n';

for (size_t idx = 1; idx < mpg.size(); idx++)
{
    std::cout << ' ' << idx << ". Is a " << std::setw(WIDTH) << vehicles[idx] << " with an mpg of " << mpg[idx] << '\n';
}

std::cout << '\n';

Now it will not matter how many vehicles are in the vector it will print all of them and the same for the mpg vector.

The "\n" at the end of line 1 is optional, but I think it makes for a nicer output. Line 8 is also optional.

You will notice that "idx" starts at (1) and not (0)zero. Since element (0) is unused everything comes out correctly. It does not matter if you use "vehicles" or "mpg" with the .size function because by the time you get here it would have been checked and they will be the same size.

Later in your code:
1
2
3
4
5
6
7
8
9
10
//Ask the user to “Select vehicle one : ” and “Select vehicle two : ”
std::cout << "Please enter your first vehicle choice. (1-5): ";
std::cin >> vec1Choice;

std::cout << "Please enter your second vehicle choice. (1-5): ";
std::cin >> vec2Choice;

//Show the user their vehicle choices
std::cout << "\nVehicle 1 is: " << vehicles.at(vec1Choice) << '\n';
std::cout << "Vehicle 2 is: " << vehicles.at(vec2Choice) << "\n\n";

Notice lines 9 and 10 do not need the (- 1) to correctly access the vector because you are not using element (0) of the 2 vectors.

This is what your program output B4 I made some changes:

Vehicle 1 is a Ford Fusion   with an mpg of 21.00
Vehicle 2 is a Honda Fit     with an mpg of 28.00
Vehicle 3 is a Jeep Renegade with an mpg of 22.00
Vehicle 4 is a Chrysler 300  with an mpg of 19.00
Vehicle 5 is a Ram           with an mpg of 16.00

Please enter your first vehicle choice. (1-5): 2
Please enter your second vehicle choice. (1-5): 4

Vehicle 1 is: Honda Fit
Vehicle 2 is: Chrysler 300

How much miles do you anticipate on driving per year?: 15000
What's the price of gas?: 2.55
Gallons per year for vehicle 1 is: 535.71
Cost of yearly fuel for vehicle 1 is: $1366.07

Gallons per year for vehicle 2 is: 789.47
Cost of yearly fuel for vehicle 2 is: $2013.16
Difference in cost of both vehicles is: $647.09
Try another combination (Y/N): y


     Goodbye!

Vehicle 1 is a Ford Fusion   with an mpg of 21.00
Vehicle 2 is a Honda Fit     with an mpg of 28.00
Vehicle 3 is a Jeep Renegade with an mpg of 22.00
Vehicle 4 is a Chrysler 300  with an mpg of 19.00
Vehicle 5 is a Ram           with an mpg of 16.00

Please enter your first vehicle choice. (1-5):

Notice that the "Goodbye!" displays even if you choose "y". Not what you want.

Now consider this for your output:

 1. Is a Ford Fusion   with an mpg of 21.00
 2. Is a Honda Fit     with an mpg of 28.00
 3. Is a Jeep Renegade with an mpg of 22.00
 4. Is a Chrysler 300  with an mpg of 19.00
 5. Is a Ram           with an mpg of 16.00

 Please enter your first vehicle choice. (1-5): 2
 Please enter your second vehicle choice. (1-5): 5

 Vehicle 1 is: Honda Fit
 Vehicle 2 is: Ram

 How much miles do you anticipate on driving per year?: 15000
 What's the price of gas?: 2.55

 Gallons per year for vehicle 1 is: 714.29
 Cost of yearly fuel for vehicle 1 is: $1821.43

 Gallons per year for vehicle 2 is: 789.47
 Cost of yearly fuel for vehicle 2 is: $2013.16

 Difference in cost of both vehicles is: $191.73


  Try another combination (Y/N): y

 1. Is a Ford Fusion   with an mpg of 21.00
 2. Is a Honda Fit     with an mpg of 28.00
 3. Is a Jeep Renegade with an mpg of 22.00
 4. Is a Chrysler 300  with an mpg of 19.00
 5. Is a Ram           with an mpg of 16.00

 Please enter your first vehicle choice. (1-5):

A few well placed "\n"s will make a big difference. And I know that you are probably just happy to get output that is correct.

Andy
Topic archived. No new replies allowed.