question about Dietel exercise

I have started taking my first course in c++.

I'm curious why I the program won't run if I don't initialize the int variables with a value. If I write "int milesDriven;" my program doesn't run.

I know it has something to do with memory but I am confused, can someone explain this please?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 #include <iostream>
using namespace std;

int main()
{
	int milesDriven =0;
	int gallonsUsed=0;
	int totalMilesDriven=0;
	int totalGallonsUsed=0;
	
	while (milesDriven != -1)
	{
		cout <<"\nEnter miles driven (-1 to quit):";
		cin >> milesDriven;
		totalMilesDriven += milesDriven;
		cout << "Enter Gallons Used: ";
		cin >> gallonsUsed;
		totalGallonsUsed += gallonsUsed;
		cout << "\nMPG this trip: " << (milesDriven / gallonsUsed);
		cout << "\nTotal MPG: " << (totalMilesDriven / totalGallonsUsed) << endl;

	}
Welcome to the forum!

Because line 11 would attempt to use an uninitialized value, your program would engender undefined behavior.
Nobody can explain your program's behavior in terms of the C++ standard if it causes undefined behavior; it's like dividing by zero and asking what you get.

Garbage in, garbage out. In other words, you got (un?)lucky.
Last edited on
But if I change the condition in the while look to true so it keeps running, and remove the "= 0" from the fundamental type declarations I still get an issue.

Your program runs but it does not save previous input because you're reading into the same variables milesDriven (line 14), gallonsUsed (line16) every time and so any information saved within them from previous input is overwritten. To need some temp variables to manage the input informations
But if I change the condition in the while look to true so it keeps running, and remove the "= 0" from the fundamental type declarations I still get an issue.

Can you show your new program?

I'm taking what you said to mean this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

int main()
{
	int milesDriven;
	int gallonsUsed;
	int totalMilesDriven;
	int totalGallonsUsed;
	
	while (true)
	{
		cout <<"\nEnter miles driven (-1 to quit):";
		cin >> milesDriven;
		totalMilesDriven += milesDriven;
		cout << "Enter Gallons Used: ";
		cin >> gallonsUsed;
		totalGallonsUsed += gallonsUsed;
		cout << "\nMPG this trip: " << (milesDriven / gallonsUsed);
		cout << "\nTotal MPG: " << (totalMilesDriven / totalGallonsUsed) << endl;

	}
}


Still causes undefined behavior for the same reason. Line 15 and 18 exhibit the same problem.
Thank you for the reply!

Sorry if I seem slow, but just to clarify, by not setting the values to 0 when I try to use the += operative it doesn't work because I'm trying to add whatever value was inputted via cin with a garbage value?
Topic archived. No new replies allowed.