comparing variables...

I am trying to exclude all values from a do loop that aren't integers, but not sure how to do this. I have nested do loops, one that will hopefully exclude all inputs except number, and then the other do loop excludes all values except 1 or 2. (Do loops are nested)

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

using namespace std;

int main () {
	int x, y;  
	        
	string Answer;
	
	x=0; 
			
	do
	{cout<< "Would you like to play a game? Type 1 to play, or 2 to terminate."<< endl; 			
          do
		{cin >> y;}
	  while (y != ???); //This is where I have the issue of comparing y to exclude anything other than numbers
	}
	while (y!=1 || y!=2);
	
	if (y != 2)
		{printf("Excellent!\n");}
	else {printf("Bummer!\n"); return 0;}
Last edited on
Hello link45jeff,

PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
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.
You can use the preview button at the bottom to see how it looks.

First you should compile your program before you post it. This would show you the errors in the program. Those errors you do not understand post the actual error message and say you do not understand it.

Read the comments in the following code and see what I did.

Understand that std::cin >> y; is known as formatted input. This means the "cin" knows that it is expecting a number as input. Anything else will cause "cin" to fail and you can use this, the while loop you will see.

Conditions that have "!=" tend to work better with "&&" than "||". Notice how I changed the while condition of the inner do/while loop and the outer do/while.

Without rewriting the whole program this is one possible solution.

Your header files are C++. The "printf" will work, but it is best not to mix C and C++ code.

Notice how I put the {}s on their own line. This makes it easier to find a missing { brace, as with your else statement, when {}s line up in the same column and the code in between is indented.

It is always a good practice to initialize your variables when defined. Doing so would eliminate the need for line 12. And for now like "answer" "x" is never used in the program.
The using statement on line 4 is a bad idea. It WILL get you in trouble some day. These links may help you understand or do a search here as there are many posts about this.

http://www.lonecpluspluscoder.com/2012/09/22/i-dont-want-to-see-another-using-namespace-xxx-in-a-header-file-ever-again/

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#user-content-sf6-use-using-namespace-directives-for-transition-for-foundation-libraries-such-as-std-or-within-a-local-scope-only

http://www.cplusplus.com/forum/beginner/230234/

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

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

int main()
{
	int x{}, y{};

	//std::string Answer; // <--- Needs header file "<string>" and is not used.

	x = 0;

	do
	{
		std::cout << "Would you like to play a game? Type 1 to play, or 2 to terminate. ";

		do
		{
			std::cin >> y;

			if (!std::cin)  // <--- Covers input for "y" that is not a number.
			{
				std::cout << "\nInvalid input.\n";
				std::cin.clear();  // <--- Clears the state bits on the stream.
				std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires heder file <limits>. Clears the input buffer.
				std::cout << "\nWould you like to play a game? Type 1 to play, or 2 to terminate. ";
				std::cin >> y;
			}
		} while (y != 1 && y != 2); //This is where I have the issue of comparing y to exclude anything other than numbers
	} while (y != 1 && y != 2);

	if (y == 2)  // <--- Changes to "==". Otherwise anything other than 2 will print.
	{
		//printf("Excellent!\n");  // <--- Should be a "std::cout". Best not to mix C and C++.
		std::cout << "\nExecllent!\n";
	}
	else
	{
		printf("Bummer!\n");
	}  // <--- Missing closing }.

	return 0;
}


Hope that helps,

Andy
@Andy
Line 28 is wrong. This way it may ask twice for the input.
@coder777 and link45jeff,

Good catch, but line 28 is correct it is line 22 that is wrong. Line 22 should start as "while" not "if". Not sure why I did that.

Looking at it again I see how it could ask for input twice when it leaves the while loop. Have not tried this yet, but thinking line 22 should be: while (!std::cin || (y != 1 && y!= 2)). My thought here is that it would stay in the while loop until either 1 or 2 is entered thus ending the inner and outer do/while loops.

I will give it a try and let you know what happens.

Hope that helps,

Andy

Edit:
Last edited on
Hello link45jeff,

Tested the while loop and it works.

Andy
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
// Guessing Game M3A1
#include <iostream>
// Use the standard Iostream to allow for input and output

using namespace std;
// Using namespace std says I used standard naming conventions within the program

int main () // Initializes the main source code
{
	int x, y;  // defines x, y as an integer variable, and allocates memory for the variable
	int num;        
	
	string Answer;// defines the variable Answer as a string, and allocates memory
	
	x=0; // define the value of x as zero
			
	do // Prevents the user from advancing until an appropriate input is entered
	{
		cout<< "Would you like to play a game? Type 1 to play, or 2 to terminate."<< endl; // ask the user if they want to play a game
		
		cin >> y; // accepts the user input and stores it for later use
		
		if (!cin.fail()) //checks the user input for a non integer type value, if an integer is input, then it does not fail, so the if statement returns why, and then breaks the loop.
			{y;
			break; (exit;)	// breaks the loop
        }
		else 
        {cout<<"Input Error!"<<endl; // displays that the user had an input error
        
        cin.clear(); // clears the input stream to allow for further user input
        
        cin.sync();} // discards remaining characters in the input stream
	}
	while (y!=1 || y!=2); // ends the do loop to continue the program, only if a 1 or 2 was entered

	if (y != 2)
		{printf("Excellent!\n");}
	else {printf("Bummer!\n"); return 0;} // The first if else statement, entering a 1 continues the program and you play the guessing game, otherwise, the program terminates. 


I googled it later last night, because it was bugging me, so this is what I did to correct the issue. This isn't the full code, because there are bunch of if else statements to ask questions to the user, and I did not want to include things I didn't have issues with. Also just found an issue with the program, with the break statement it would accept any integer and continue the program, so I changed the || to && and changed break; to exit;
Last edited on
I also went through after posting this and cleaned up the code a bit to make the {} on their own lines. I could probably change printf to cout << pretty easily, I used printf for decimals, but since have been using set precision(), and showpoint.
Hello link45jeff,

I tried your new code and it does not work. After I put a closing brace for main it did not compile.

Line 25 you have (exit;) it should be exit(1);. Zero is generally used to indicate a normal exit whereas any number above zero indicates there was a problem. If you would have multiple "exit"s in a program using a different number in each exit helps to figure out what went wrong and where you should look. Also because of "break" "exit" is never reached.

Line 23. Your use of !cin.fail() is not the best use if this function. Actually it is backwards. As long as you enter a number 0 - 9 you enter the then part of the if/else. Which says:
1
2
y;
break;

What is the point of "y;"? It does nothing. The "break" statement will be executed before the "exit", so the exit is never reached.

The "cin.sync()" I do not believe is working the way you are thinking. If this part of your code is reached it creates an endless loop. The "std::cin.ignore" that I showed you works better.

Line 34. The way it is written it will always be true. When I entered a letter and reached line 34 the value of "y" was "-858993460" which makes the condition true thus creating an endless loop because "y" is never changed.

Line 36. Will print "Excellent!" for any number that is not "2". Not what you want.

Let's see if I can clear up your understanding of some of the comments in your program.

using namespace std;
// Using namespace std says I used standard naming conventions within the program
To be blunt it says that you are lazy and do not want to learn anything. Now is the time, when it is easier, to be learning what is in the "std" namespace and how to qualify things like: "std::cout", "std::cin" and "std::endl". The "std::" is how you tell the compiler that "cout", "cin" and "endl" are in the standard name space. In an earlier post I gave you three links to read on the "using" statement. It is worth your time to read them.

int x, y; // defines x, y as an integer variable, and allocates memory for the variable
Yes it does except that those variables have what ever value that was left in that memory location. Most times on my computer that value for an int is ""-858993460". Sometimes this is not a problem, but most times it is. You should always initialize your variables when they are defined. From C++11 on this can be done with the uniform initializer of {}. Putting something between the {}s will give the variable that value when created.

Line 17.
do // Prevents the user from advancing until an appropriate input is entered
A good idea, but your code does not do this. I can input anything from 0 - 9 and it works. Input a letter and it creates an endless loop.

Line 23.
//checks the user input for a non integer type value, if an integer is input, then it does not fail, so the if statement returns why, and then breaks the loop.
The if statement returns nothing and "y;" does nothing. The "break" will break out of the for loop. That part is correct.

Line 30.
cin.clear(); // clears the input stream to allow for further user input
No this clears the state bits associated with the stream only to allow further use of the stream. This would work for any type of input stream.

Line 32.
cin.sync();} // discards remaining characters in the input stream
First it is not the input stream you are working with it is the input buffer. If you want to clear the input buffer it is best to use the "std::cin.ignore(...)" I showed you earlier. When I was testing the program I switched the "cin.sync" for the "std::cin.ignore(...)" and it worked much better.

Line 34.
// ends the do loop to continue the program, only if a 1 or 2 was entered
Not really. As an || condition this will always be true.

Line 38.
// The first if else statement, entering a 1 continues the program and you play the guessing game, otherwise, the program terminates.
Not really. Entering any number other than 2 will continue the game and 2 will exit.

I hope that gives you something to think about and a better understanding of some of your comments,

Andy
Try this. It works for both int and double.

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
/**
 * @file    helper.cpp
 * @author  blongho
 * @date    2018-02-15
 * @brief   Get a valid number from a user
 * */
#include <iostream>
#include <string>
#include <sstream>
#include <cctype>

/**
 * Get a valid integer or double
 * @param   text Message to display to the user
 * @param   min The minimum value in the range
 * @param   max The maximum number in the range 
 */
template<class T>
T getNumber(const char * text, const T &min, const T &max);

bool isAllNumbers(const std::string &input); // check that all char isdigit

int main()
{
  int intNum = getNumber("Enter an integer: ", 0, 5);
  
  std::cout << "You entered: " << intNum << std::endl;
  
  double dbNum = getNumber("Enter a double: ", 0, 5);
  
  std::cout << "You entered: " << dbNum << std::endl;

}


bool isAllNumbers(const std::string & input)
{
	for (const auto &c : input) {
		if (!isdigit(c)) {
			return false;
		}
	}
	return true;
}

template<class T>
T getNumber(const char * text, const T &min, const T &max)
{
	std::string input{};
	T num{};
	while (true) {
		std::cout << text << " [" << min << " - " << max << "]: ";
		std::getline(std::cin, input);
		std::stringstream ss(input);
		if (!isAllNumbers(ss.str())) {
			std::cout << "Invalid input. Try again!\n";
		}
		else {
			if (isAllNumbers(ss.str()) && ss >> num) {
				if (num >= min && num <= max) {
					break;
				}
				else {
					std::cout << "Out of range. Try again!\n";
				}
			}
		}
	}
	return num;
}
Last edited on
The (exit;) was a fix I did to the code, also I edited the while statement to while (y=!1 && y!=2) which fixed the number glitch. Also the entering a letter was fixed byt the cin.fail().

The y on line 24, was just because I wasn't sure if there had to be anything there or not for the if statement. The break; caused the program to terminate the loop, resulting in any number working.

My text book does not have most of this stuff, so I was reading of posts online, so some of the information could be wrong, but I submitted my assignment and cannot change it, so I will have to keep it in mind for the next. I compiled my program and it worked fine with all the things I was trying to do, like I said I made some tweaks. Here is the final iteration of the program.

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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
// Guessing Game M3A1
#include <iostream>
// Use the standard Iostream to allow for input and output

using namespace std;
// Using namespace std says I used standard naming conventions within the program

int main () // Initializes the main source code
{
	int x, y;  // defines x, y as an integer variable, and allocates memory for the variable     
	
	string Answer;// defines the variable Answer as a string, and allocates memory
	
	x=0; // define the value of x as zero
			
	do // Prevents the user from advancing until an appropriate input is entered
	{
		cout<< "Would you like to play a game? Type 1 to play, or 2 to terminate.\n"<< endl; // ask the user if they want to play a game
		
		cin >> y ; // accepts the user input and stores it for later use
		
		cout << endl;
		
		if (!cin.fail()) //checks the user input for a non integer type value, if an integer is input, then it does not fail, so the if statement returns why, and then breaks the loop.
		{	
			y;      // if a valid input is found, the if statment returns the value of the y variable
			exit;	// exits the if statement and then y is evaluated in the do while loop.
        }
        
		else 
        {
			cout<<"Input Error!"<<endl; // displays that the user had an input error
        
        	cin.clear(); // clears the input stream to allow for further user input
        
        	cin.sync(); // discards remaining characters in the input stream
		} 
		
	} while (y!=1 && y!=2); // ends the do loop to continue the program, only if a 1 or 2 was entered

	if (y != 2)
	{
		cout <<"Excellent!\n" << endl;
	}
	
	else 
	{
		cout << "Bummer!\n"; return 0; // The first if else statement, entering a 1 continues the program and you play the guessing game, otherwise, the program terminates.
	} 
	
	cout << "Evaluate the folowing proverbs. Answer True if the proverb is correct, or False if the proverb is incorrect then hit enter. At the end of the game we will rate your performance.\n" << endl;
	
	cout << "True or False: The squeaky wheel gets the grease." << endl; // User instructions, and guidelines on how to play the game. Informs user there will be an evaluation of their performance

	cin >> Answer; // Accepts user insput for the variable Answer, and stores it for later use.
	cout << endl;
	
	if (Answer == "True" || Answer == "true" || Answer == "T" || Answer == "t")
		{
			x = ++x;
		} 
	else 
		{
			x = x;
		} 
	
	cout << "True or False: Cry and you cry alone." <<endl;
	cin >> Answer;
	cout << endl;
	
	if (Answer == "True" || Answer == "true" || Answer == "T" || Answer == "t")
		{
			x = ++x;
		}
	else 
		{
			x = x;
		}

	cout << "True or False: Opposite attract." << endl;
	cin >> Answer;
	cout << endl;
	
	if (Answer == "False" || Answer == "false" || Answer == "F" || Answer == "f")
		{
			x = ++x;
		}
	else 
		{
			x = x;
		}

	cout << "True or False: Spare the rod and spoil the child." <<endl;
	cin >> Answer;
	cout << endl;

	if (Answer == "False" || Answer == "false" || Answer == "F" || Answer == "f")
		{
			x = ++x;
		}
	else 
		{
			x = x;
		}

	cout << "True or False: Actions speak louder than words." << endl;
	cin >> Answer;
	cout << endl;
	
	if (Answer == "True" || Answer == "true" || Answer == "T" || Answer == "t")
		{
			x = ++x;
		}
	else 
		{
			x = x;
		}
	
	cout << "True or False: Familiarity breeds contempt." <<endl;
	cin >> Answer;
	cout << endl;
	
	if (Answer == "False" || Answer == "false" || Answer == "F" || Answer == "f")
		{
			x = ++x;
		}
	else 
		{
			x = x;
		}
	
	cout << "True or False: Marry in house, repent at leisure." << endl;
	cin >> Answer;
	cout << endl;

	if (Answer == "True" || Answer == "true" || Answer == "T" || Answer == "t")
		{
			x = ++x;
		}
	else 
		{
			x = x;
		} 
	/* The meat and potatoes of the program is a series of if else statements with the imposed question. The user guesses the answer writing either True or true, 
	or False or false, either of these answers are excepted. Once the user inputs thier answer, the computer stores the data and then opens the if statement. 
	The if statement evaluates the variable answer and accepts either of the two ways to write the answer.
	If the question is answered correctly a prefix increment is used to add to the value of x. I used prefix increment operator, to add one to x within that operation, but if the answer 
	is wrong x = x. The process is repeated untill all questions are answered. */
		
	cout << "Congratulations you have completed the game.\n" << "Your final score is: " << x << " out of a possible 7!\n" << endl; 
	// Congratulate the user on their performance, and display their score out of 7
	
	switch (x) // The switch statement evaluates the value of x, and based on its value performs the specific output for the case value.
	{
	case 0:
		cout << "You chose... poorly.\n";
		break;
	case 1:
		cout <<"You chose... poorly.\n";
		break;
	case 2:
		cout << "You chose... poorly.\n";
		break;
	case 3:
		cout <<"You chose wisely.\n";
		break;
	case 4:
		cout << "You chose wisely.\n";
		break;
	case 5:
		cout <<"You did an excellent job!\n";
		break;
	case 6:
		cout << "You did an excellent job!\n";
		break;
	case 7:
		cout <<"You got a perfect score!\n";
		break;
	}
		/*	Switch statment is used to evaluate x, and based on each case from 0-7 (all the possibilities) all outcomes displays a message based on performance. 
			Breaks are included to prevent multiple messages from appearing for the wrong value of x. */
	
	return 0; // terminates the program normally
	
}

does the statement work the same way for excluding numbers? I am working on a different program, and using your solution, it should accept a char, and not a number, but if I enter a number it loops back to the beginning.
Here's what I have so far, the last loop is where the issue lies:


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
// M4A1 Math expressions
#include <iostream> 
#include <iomanip> 
#include <limits>



int main () 
{
	std::cout << std::setprecision (2);   
	std::cout << std::fixed << std::showpoint; 
	double unitPrice, quantityPurchased, purchasePrice, salesTax; 	
        char stop; 
	
	do 
	{
			do 
			{
				std::cout << "Enter a unit price for product between $0 and $1000: \n "; 
				do
				{			
					std::cin >> unitPrice; 				
					if (!std::cin) 
                                       {	
					std::cout << "\n Invalid Input\n";
                                        std::cin.clear();
                                        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
                                        std::cout << "\nEnter a unit price for product between $0 and $1000: \n ";
                                        std::cin >> unitPrice;
					}
				}
				while (!std::cin);	
			}
			while (unitPrice < 0 || unitPrice > 1000); 
			
		do 
			{
				std::cout << "Enter the amount of product purchased, this cannot be a negative number: "; 
				
				do
				{
					std::cin >> quantityPurchased; 				
					if (!std::cin) 
					{	
					std::cout << "\n Invalid Input\n";
                                        std::cin.clear();
                                        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
                                        std::cout << "\nEnter the amount of product purchased, this cannot be a negative number:\n ";
                                        std::cin >> quantityPurchased;
					}
				}
				while (!std::cin);	
			}
		while (quantityPurchased <= 0); 
		
		purchasePrice = unitPrice * quantityPurchased; 
	
		salesTax = purchasePrice * .05; 
	
		std::cout << "The purchase price is: $" << purchasePrice << "\n" << "The sales tax on the pruchase is: $" << salesTax << "\n" << "The total cost is: $" << salesTax + purchasePrice << std::endl;
		
		std::cout << "If you would like to continue enter y or Y, to quit enter n or N: "; 					
				do
				{
					std::cin >> stop;
									
					if (!std::cin) 					
                                       {	
				       std::cout << "\n Invalid Input\n";
                                       std::cin.clear();
                                       std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
                                       std::cout << "\n If you would like to continue enter y or Y, to quit enter n or N :\n ";
			               std::cin >> stop;
					}
				}
				while (!std::cin); 
	} 
	while (stop != 'n' && stop != 'N');
In your loops you have still the problem that it asks twice. Try this:
1
2
3
4
5
6
7
8
9
10
11
			do 
			{
				std::cout << "Enter a unit price for product between $0 and $1000: \n "; 
					if (!(std::cin >> unitPrice)) 
                                       {	
					std::cout << "\n Invalid Input\n";
                                        std::cin.clear();
                                        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
					}
			}
			while ((!std::cin) || unitPrice < 0 || unitPrice > 1000);


Entering a char cannot fail. It loops back to the beginning because you placed the do there.
I do not see an std::cin statement in your code, i put it before the if statement, and no I have other issues with the statements after modifying to more match your coding. @coder777

I'm not sure where the issues are now, so I have to go through and try a bunch of different combinations.
This works, but the only thing that gets me, is when I ask for an integer and a decimal is input it accepts the input and gives an error when it asks for the min and max... not sure why.

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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
// M4A1 Math expressions
#include <iostream> 
#include <iomanip> 
#include <limits>

int main () // initiates the source code
{
	std::cout << std::setprecision (2);
	std::cout << std::fixed << std::showpoint;
	double unitPrice, quantityPurchased, purchasePrice, salesTax; 
	char stop; 	
	do 
	{
			do 
			{
				std::cout << "Enter a unit price for product between $0 and $1000: \n "; // tells the user to to enter the value
							
					std::cin >> unitPrice; // accepts user input for the variable unitPrice, and stores it as such
				
					if (!std::cin) //checks the user input for a non integer type value, if an integer is input, then it does not fail, so the if statement returns why, and then breaks the loop.
					{	
						std::cout << "Invalid Input\n";	// exits the if statement and then y is evaluated in the do while loop.
						std::cin.clear();  // <--- Clears the state bits on the stream.
						std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires heder file <limits>. Clears the input buffer.
						std::cout << "Enter a unit price for product between $0 and $1000: \n "; // tells the user to to enter the value
						std::cin >> unitPrice;
					}
					
			}
			while (!std::cin || (unitPrice < 0 || unitPrice > 1000)); // this loop will continue to execute until a number is entered that is between 0 and 1000.
		// once the input satisfies the conditions, the program moves onto the next step.
	
		do // this do loop will execute until a positive value is entered
			{
				std::cout << "Enter the amount of product purchased, this cannot be a negative number: "; // tells the user to input a positive number
									
				std::cin >> quantityPurchased; // accepts user input for the variable quantityPurchased, and stores it as such
				
				if (!std::cin) //checks the user input for a non integer type value, if an integer is input, then it does not fail, so the if statement returns why, and then breaks the loop.
					{	
						std::cout << "Invalid Input\n" <<std::endl;	// exits the if statement and then y is evaluated in the do while loop.
						std::cin.clear();  // <--- Clears the state bits on the stream.
						std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires heder file <limits>. Clears the input buffer.
						std::cout << "Enter the amount of product purchased, this cannot be a negative number: ";
						std::cin >> quantityPurchased;
					}
			}
		while (!std::cin || quantityPurchased <= 0); // loop will end once a positive number is entered for quantity and the program will continue
		
		purchasePrice = unitPrice * quantityPurchased; // variable purchasePrice is calculated and stored
	
		salesTax = purchasePrice * .05; // variable salesTax is calculated and stored, sales tax is 5%
	
		std::cout << "The purchase price is: $" << purchasePrice << "\n" << "The sales tax on the pruchase is: $" << salesTax << "\n" << "The total cost is: $" << salesTax + purchasePrice << std::endl;
		// program outputs the data for the transaction to the user displaying purchase price, sales tax, and total cost
		
			do
			{
					std::cout << "If you would like to continue enter y or Y, to quit enter n or N: "; // tells the user to input a character value so the program can evaluate if the user would like to continue
					std::cin >> stop;
									
					if (!std::cin.fail()) //checks the user input for a non integer type value, if an integer is input, then it does not fail, so the if statement returns why, and then breaks the loop.
					{	
						std::cout << "Invalid Input\n";	// exits the if statement and then y is evaluated in the do while loop.
						std::cin.clear();  // <--- Clears the state bits on the stream.
						std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires heder file <limits>. Clears the input buffer.
					}
			}
			while (!std::cin.fail() && stop != 'y' && stop != 'Y' && stop != 'N' && stop != 'n'); 
	} 
	while (stop != 'n' && stop != 'N'); // finishing up the first do loop, based on user input, the program can start over and repeat if they enter any character of then n or N, once complete the program moves onto the next segement
	
	int num, i, min, max, product; // sets those variables as integer, and allocates memory for them
		
	do // allows the user to try the multiplication table as many times as they want before
	{
		do
		{
			std::cout << "Enter any integer then press enter (only enter numbers without decimals): " << std::endl; // tells the user to input an integer
		
			std::cin >> num; // accepts the user input for the variable num and stores it for later use
				
				if (!std::cin) //checks the user input for a non integer type value, if an integer is input, then it does not fail, so the if statement returns why, and then breaks the loop.
					{	
						std::cout << "Invalid Input\n" <<std::endl;	// exits the if statement and then y is evaluated in the do while loop.
						std::cin.clear();  // <--- Clears the state bits on the stream.
						std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires heder file <limits>. Clears the input buffer.
						std::cout << "Enter any integer then press enter: ";
						std::cin >> num;
					}
		}
		while (!std::cin); 
		
		do
		{
			std::cout << "Enter two numbers, a low value and a high value then press enter: " << std::endl; // tells the user to input a max and min value
		
			std::cin >> min >> max; //accepts the user input for the variables min and max
			
			if (!std::cin) //checks the user input for a non integer type value, if an integer is input, then it does not fail, so the if statement returns why, and then breaks the loop.
					{	
						std::cout << "Invalid Input\n" <<std::endl;	// exits the if statement and then y is evaluated in the do while loop.
						std::cin.clear();  // <--- Clears the state bits on the stream.
						std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires heder file <limits>. Clears the input buffer.
						std::cout << "Enter two numbers, a low value and a high value then press enter:";
						std::cin >> min >> max;
					}
		}
		while (!std::cin);
		
		for (i= min; i <= max; i++) // This for statement tells the computer to repeat the program if i <= max, once the max value specified by the user is reached the program runs through the code one last time and finished
		// i = min, so the program inserts at this point, for example user inputs 1 for min and 2 for max, program starts at 1, runs through the code, reaches two, runs through and then completes the loop.
		{
			product = num * min; // defines product as user input num * user input min
			std::cout << num << " x " << min << " = " << product << std::endl; // displays num * min = product
			min++;	// after the code is complete it adds 1 to the value of min, after the last run the min > max, and the loop will not run again
		}
		
		do
			{
					std::cout << "If you would like to continue enter y or Y, to quit enter n or N: "; // tells the user to input a character value so the program can evaluate if the user would like to continue
					std::cin >> stop;
									
					if (!std::cin) //checks the user input for a non integer type value, if an integer is input, then it does not fail, so the if statement returns why, and then breaks the loop.
					{	
						std::cout << "Invalid Input\n";	// exits the if statement and then y is evaluated in the do while loop.
						std::cin.clear();  // <--- Clears the state bits on the stream.
						std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires heder file <limits>. Clears the input buffer.
					}
			}
			while (!std::cin && stop != 'y' && stop != 'Y' && stop != 'N' && stop != 'n'); 
	} 
	while (stop != 'n' && stop != 'N');
		
	return 0; // terminates the program normally
}
Topic archived. No new replies allowed.