I have to write a program in C++ and am unsure on how to return to the top after an error. For example, I have the user input 2 integers, if the 2nd integer is smaller than the first i have an error stating pls enter in a number larger than the first, but from here I do not know what code to enter to have the question be asked again / send to the beginning / top of the code?
if (num1 > num2)
cout << "You second number must be larger than your first number." << endl;
Problem
I do not know what code to enter to have the question be asked again / send to the beginning / top of the code?
Well almost always when you have that situation, you will use a while loop. This loops over the block if the condition is true.
#include <iostream>
#include <string>
int main()
{
int num1;
int num2;
do {
std::cout << "What is first num? ";
std::cin >> num1;
std::cout << "What is second num? ";
std::cin >> num2;
} while (num1 < num2);
}
Basically, what happens is first you have to declare the integers num1 and num2. Then you have a do while loop! Well this executes the code in the do block before checking for the condition! First we ask for the two user inputs, then we check for the condition. Let's look at the condition carefully:
while(num1<num2)
This means if the first number the user entered is less than the second number, loop through the while block. The while block does the same thing until num1 becomes greater than num2!
Here is a compiled version (GCC).
Additional Exercises
icodecool
Tutorial
CS_PDF
References
cpprefrence
MSDN
Flow Control Tutorial
Glossary:
do-while loop:
Executes a statement repeatedly until the value of the expression becomes false. The test takes place after each iteration.
Syntax
attr(optional) do statement while ( expression ) ;
attr(C++11) - any number of attributes
expression - any expression which is contextually convertible to bool. This expression is evaluated after each iteration, and if it yields false, the loop is exited.
statement - any statement, typically a compound statement, which is the body of the loop
Try:
cout << "Enter number 2: ";
cin >> num2;
while (num1 > num2) {
cout << "You second number must be larger than your first number." << endl;
cout << "Enter number 2: ";
cin >> num2;
}
int num1 = 0, num2 = 0;
do
{
cout << "num1: ";
cin >> num1;
cout << "num2: ";
cin >> num2;
if(num2 < num1)
cout << "error num2 is smaler than num1" << endl;
}while(num2 < num1);
Related
I am doing a programming exercise for my beginner class. The exercise is to write a c++ program that mimics a calculator.
This is the beginning of my code (not the entire code, just the beginning):
#include <iostream>
#include <string>
using namespace std;
int num1;
int num2;
double answer;
string op;
int main(void)
{
// Write your main here
cout << "Enter a number" << endl;
cin >> num1;
//Prompt user to enter an operator
cout << "Enter an operator (+, -, *, or /)" << endl;
cin >> op;
//Prompt user to enter another number
cout << "Enter another number" << endl;
cin >> num2;
//Determine whether or not addition was selected
if (op == "+")
answer = (num1 + num2);
cout << answer;
else
Regardless of what statements I put after that "else" statement, I am getting an error message that reads "Illegal else without matching if."
BUT, if I remove the preceding "cout << answer;" line, then the program compiles and runs fine.
What am I doing wrong?
Always use scope { ... } with if statements and for/while loops.
The problem is, if you don't use scope, then your if only encompasses the next statement underneath it (answer = (...). Because of this, the cout statement will happen ALL THE TIME, and the else isn't associated with the if statement. If you always use scope, you never have to worry about this.
if (op == "+") {
answer = (num1 + num2);
cout << answer;
}
You need to use {} braces on your if statement in order to execute multiple statements:
//Determine whether or not addition was selected
if (op == "+")
{
answer = (num1 + num2);
cout << answer;
}
else
...
You need to add the {} brackets between if and else because you have more than one statement.
This is what the compiler understands from your code:
if (op == "+")
answer = (num1 + num2);
cout << answer;
else
What you should do:
if (op == "+") {
answer = (num1 + num2);
cout << answer;
}
else
I am very new to C++, and I am trying to make a simple number reading program, and it is functional. However, I keep getting a '1' input in between my other output lines. How can I remove these 1s?
Here is my code:
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
printf("\nThe following program should enter integer numbers until a negative number.\n");
printf("The output is the smallest number input as well as the number of numbers.\n\n");
printf("Please enter a number -----> ");
int n = 0;
int num;
cin >> num;
int smallest = num;
while (num >= 0)
{
n++;
if (num < smallest)
{
int smallest = num;
}
cout << "Please enter another number -----> " << (cin >> num) << endl;
}
while (num < 0)
{
cout << "Negative number entered. Calculating Results...\n\n";
cout << "Of " << n << " numbers read, the smallest number is " << smallest << ".\n";
return 0;
}
}
And the output looks like this (I randomly input some test numbers):
The following program should enter integer numbers until a negative number.
The output is the smallest number input as well as the number of numbers.
Please enter a number -----> 3
Please enter another number -----> 4
1
Please enter another number -----> 8
1
Please enter another number -----> -1
1
Negative number entered. Calculating Results...
Of 3 numbers read, the smallest number is 3.
'''
How do I remove these 1s, and why are they happening?
(cin >> num)
This expression does two things:
The cin input stream waits for user input and puts that value into num.
The operator overload for >> on an istream returns a istream&, a reference to the cin instance.
(This is why you can repeat the >> operator on one line to get multiple values.)
That expression is in a place where the cout << operator is expecting an argument, so the conversion from istream& to some sort of printable character is resulting in a 1 being added to the cout stream.
The reason the 1 is on a new line is because the terminal/console you're using requires you to use the Enter key (which adds a new line) to enter a value.
I tried this in my c++ console, and had to make a change in line 25. Instead of -
cout << "Please enter another number -----> " << (cin >> num) << endl;
I used this -
cout << "Please enter another number -----> ";
cin >> num;
And there were no explicit error messages. Also, no 1s.
I am a bit concerned about the actual code though. The logic is not correct.
How was you able to compile this code?
Doc.cpp:26:60: error: no match for ‘operator<<’ (operand types are ‘std::basic_ostream’ and ‘std::basic_istream::__istream_type {aka std::basic_istream}’)
cout << "Please enter another number -----> " << (cin >> num) << endl;
I have to change this line:
cout << "Please enter another number -----> " << (cin >> num) << endl;
into this:
cout << "Please enter another number -----> ";
cin >> num;
cout << endl;
in order to make the code compilable, at least for me.
Also, the last while loop is unnecessary, since if num is not bigger or equal to zero, it could only be a negative number.
I am writing a code for class that asks the user to input a size that is an odd number equal to or greater than 7. I have been able to make that part of my code work successfully. However, the next part consists of asking the user to enter a specific letter, in this case 'c'. If they do not enter 'c' then the loop should ask them to input another character. Whenever I run this code, it is creating an infinite loop whether I enter 'c' or another letter. I think my expression in my second while loop is incorrect, but I haven't been able to find a lot of information regarding this that could help me.
#include <iostream>
using namespace std;
int main() {
int s, l;
cout << "Welcome to the letter printer." << endl;
cout << "Enter the size: " << endl;
cin >> s;
while (s < 7 || s%2==0 || s<0)
{
cout << "Invalid size. Enter the size again: " << endl;
cin >> s;
}
cout << "Enter the letter: " << endl;
cin >> l;
while (l != 'c')
{
cout << "Invalid letter. Enter the letter again: " << endl;
cin >> l;
}
return 0;
}
because you are getting char for int variable
wrong:
int s, l;
right one:
int s;
char l;
what is why it goes on infinite loop in second while
explanation for infinite loop
This is how basic_istream works. In your case when cin >> l gets
wrong input - failbit is set and cin is not cleared. So next time it
will be the same wrong input. To handle this correctly you can add
check for correct input and clear&ignore cin in case of wrong input.
incorporated from here
I just can't seem to get this program to work properly. I can get it to accept two integers and print them to the screen. But I can't get the program to terminate when the '|' is used. Once that its entered it loops infinitely. Here is the code that I have so far:
#include "../../std_lib_facilities.h"
int main()
{
int num1 = 0;
int num2 = 0;
char counter = '\0';
cout << "Please enter two integers and press enter. \n";
bool test = true;
while (counter != '|')
{
cin >> num1 >> num2;
cout << "Your numbers are: " << num1 << " " << num2 << endl;
if (cin.fail())
{
cout << "Goodbye!\n";
test = false;
}
else (counter != '|');
cout << "Enter more numbers or press '|' to exit.\n";
}
system("pause");
}
You are using the wrong condition in your while loop. You are never changing counter so the loop will never end. However you do change test to false in the while loop if the input fails. You can change the condition of the while loop to use test instead like
while(test)
{
//...
}
Since counter is no longer being used you can get rid of it completely.
Please note that unless you change to taking in string and parsing the input any input that will cause cin to fail will end the loop not just a |.
I've recently started working through the "c++ primer 5th Edition". I'm currently on the following exercise:
Exercise 1.11:
Write a program that prompts the user for two integers.
Print each number in the range specified by those two integers.
I have written the following code as a solution :
#include <iostream>
int main(){
int num1 = 0, num2 = 0;
std::cout << std::endl << "Please enter two numbers to find a range between" << std::endl;
std::cin >> num1 >> num2;
if (num1 < num2)
while (num1 <= num2){
std::cout << std::endl << num1;
++num1;
}
if (num2 < num1)
while (num2 <= num1){
std::cout << std::endl << num2;
++num2;
}
if (num1 == num2)
std::cout << std::endl << num1;
std::cout << std::endl;
However when I input the numbers, the output is not quite correct;
Sample input:
Please enter two numbers to find a range betweem
>> 1 5
Sample output:
1
2
3
4
5
5
6
What I don't understand, is that if the first number i input is larger than the first (e.g. num1 > num2), then the program produces the desired result, eg:
Please enter two numbers to find a range between
>> 5 1
1
2
3
4
5
What is particularly confusing is that, when I swap the order of the conditional statements, the first example will work correctly and the second will produce incorrect output.
Just to be clear, I'm aware of a cleaner, correct solution to this exercise. I would just like to know the reason that my program functions this way.
I'd very much appreciate an explanation!
Its so simple.
Just add 'else' for the bottom two if loops
Basically you need to go through only 1 'if' loop, but your program goes through each 'if' loop
Actually you are increamenting your num1 in the first condition when all iterations of while loop completed your second if condition gets true because its the loop exit condition of first if(i.e. num1 <= num2), so your second if triggered and print the last 5 6 .
While in second case your first if not triggered and you reach the second if and hence your flow works properly
As Technoid said, add else statements. Your code should now become:
#include <iostream>
int main(){
int num1 = 0, num2 = 0;
std::cout << std::endl << "Please enter two numbers to find a range between" << std::endl;
std::cin >> num1 >> num2;
if (num1 < num2)
while (num1 <= num2){
std::cout << std::endl << num1;
++num1;
}
else if (num2 < num1)
while (num2 <= num1){
std::cout << std::endl << num2;
++num2;
}
else if (num1 == num2)
std::cout << std::endl << num1;
/* Alternatively for (num1 ==num2) use:
else
std::cout << std::endl << num1;
*/
std::cout << std::endl;
}