I am currently working on a programming assignment and am having trouble with checking the input placed by the user. The program is where you enter two positive numbers only, however when I enter a character, such as 'a' as my first "number", the program accepts it and outputs it as if I entered a zero. It should output "Invalid number: Numbers must be positive integer." Can someone tell me what I am doing wrong? Thank you!
//Program where user enters two positive numbers
//and program will display various things.
#include <iostream>
using namespace std;
int main()
{
//Displays information of what program will do
cout<< "Practice with iterations\n\n"
<< "The function of this program is, given 2 positive numbers, the"
<< " program";
cout<< "\nwill display the following\n\n";
cout<< "\t1. All even numbers between firstNum and secondNum.\n"
<< "\t2. All odd numbers between firstNum and secondNum.\n"
<< "\t3. Sum of all even numbers between firstNum and secondNum.\n"
<< "\t4. Sum of all odd numbers between firstNum and secondNum.\n"
<< "\t5. All prime numbers between firstNum and secondNum.\n"
<< "\t6. Factorial of the secondNum.\n"
<< "\t7. The numbers and their squares between firstNum and "
<< "secondNum."<< endl;
//Declare first and second number variables
int firstNum;
int secondNum;
bool flag= true; //Set to true
char x; //Use to see if value entered is letter
//Ask user to input values
cout<< "\n\nEnter the first number:\t\t";
cin>> firstNum;
if (cin.fail())
{
cin.clear();
cin.ignore(256,'\n');
flag= 0;
}
cout<< "Enter the second number:\t";
cin>> secondNum;
if (cin.fail())
{
cin.clear();
cin.ignore(256,'\n');
flag= 0;
}
//If user puts wrong input
if (firstNum>secondNum)
cout<< "\nError: First number must be < second number.\n";
else if (firstNum<0 || secondNum<0)
cout<< "\nError: Invalid number: Number must be positive.\n";
else if (firstNum==x || secondNum==x)
cout<< "\nError: Invalid number: Numbers must be positive integer.\n";
else
{
cout<< "\nYou entered: "<< firstNum<< " and "<< secondNum;
}
return 0;
}
if (firstNum==x || secondNum==x)
cout<< "\nError: Invalid number: Numbers must be positive integer.\n";
this test is wrong x is not initialized and it doesn't really make sense..plus you have used the flag to test the fail input case i assume so your code should be like this
#include <iostream>
using namespace std;
int main()
{
//Displays information of what program will do
cout << "Practice with iterations\n\n"
<< "The function of this program is, given 2 positive numbers, the"
<< " program";
cout << "\nwill display the following\n\n";
cout << "\t1. All even numbers between firstNum and secondNum.\n"
<< "\t2. All odd numbers between firstNum and secondNum.\n"
<< "\t3. Sum of all even numbers between firstNum and secondNum.\n"
<< "\t4. Sum of all odd numbers between firstNum and secondNum.\n"
<< "\t5. All prime numbers between firstNum and secondNum.\n"
<< "\t6. Factorial of the secondNum.\n"
<< "\t7. The numbers and their squares between firstNum and "
<< "secondNum." << endl;
//Declare first and second number variables
int firstNum;
int secondNum;
bool flag = true; //Set to true
//Ask user to input values
cout << "\n\nEnter the first number:\t\t";
cin >> firstNum;
if (cin.fail())
{
cin.clear();
cin.ignore(256, '\n');
flag = 0;
}
cout << "Enter the second number:\t";
cin >> secondNum;
if (cin.fail())
{
cout << "lol" << endl;
cin.clear();
cin.ignore(256, '\n');
flag = 0;
}
if (flag) {
if (firstNum > secondNum)
cout << "\nError: First number must be < second number.\n";
else if (firstNum < 0 || secondNum < 0)
cout << "\nError: Invalid number: Number must be positive.\n";
else
{
cout << "\nYou entered: " << firstNum << " and " << secondNum;
}
}
else cout << "Error input" << endl;
return 0;
}
If there is an error in reading the input, you have the first steps correctly accounted for -- clear the input stream and clear the error state of cin. What you are missing is reading something valid into the variable. For that you need a loop.
while (true )
{
//Ask user to input values
cout<< "\n\nEnter the first number:\t\t";
// Try to read the input. If it is successful, break out of the loop.
if ( cin>> firstNum )
{
break;
}
// Clear the error flag. Clear the input stream. Try again.
cin.clear();
cin.ignore(256,'\n');
}
Do the same thing for the second number.
Related
Hello im stuck at SUBTRACTION AND DIVITION AND I CANT FIGURE OUT WHAT CODE to use because when I try to subtract 10 i inputed it then it will loop since the while condition is not meet which it needs to be negative to terminate the loop and i inputed 2 for the second number then loop again then i putted -number which lead to terminate loop and subtract all the number but the result is -12 its always wrong in every number cant figure out why Please help
Also with divition, only my addition is working havent started the divition cuz i cant figure out how
#include <iostream>
using namespace std;
int amt2, total;
double subNumbers();
double amt=1;
double number=0;
int main() {
int chc=0;
int amt = 0;
int amt2 = 1;
cout << "Welcome again User!\n";
cout << "______________________________________________________________\n" << endl;
cout << "Mathematical Operations(Improved):\n\n";
cout << "\t[1]-Addition" << endl;
cout << "\t[2]-Subtraction" << endl;
cout << "\t[3]-Multiplication" << endl;
cout << "\t[4]-Division\n" << endl;
cout << "______________________________________________________________\n" << endl;
cout << "Type the number corresponding to your chosen operation: ";
cin >> chc;
```
switch (chc) {
case 1:
```
system ("cls");
cout << "\n\n\tOperation chosen: Addition";
cout << "\n______________________________________________________________" << endl;
cout << "\n\nInput positive numbers to use the operation and input a negative number to end the operation.\n\n";
cout << "Enter your number: ";`
cin >> number;
while (number >= 0) {
// add all positive numbers
amt += number;
// take input again if the number is positive
cout << "Enter another number: ";
cin >> number;
}
// display the sum
cout << "\nThe sum of all the numbers is: " << amt << endl;
break;
```
case 2:
system ("cls");
cout << "\n\n\tOperation chosen: Subtraction";
cout << "\n______________________________________________________________" << endl;
cout << "\n\nInput positive numbers to use the operation and input a negative number to end the operation.\n\n";
do{
cout << "Enter your number: ";
cin >> number;
amt=number-number ;
}while (number >= 0);// subtract all positive numbers
// display the difference
cout << "\nThe difference of all the numbers is: "<<amt;
return 0;
}}
```
enter code here
You are subtracting number from number:
amt = number - number; // Which is always 0
So that's why amt == 0 always.
So just change your loop to this:
while (true) {
cout << "Enter your number: ";
cin >> number;
if (number < 0) break;
if (amt == 0) amt = number;
else if (number >= 0) amt -= number;
}
What this does is that if amt == 0, then set amt to number. I have done this because as the default value of amt is 0 (due to int amt = 0;), when amt == 0, then we can assume that the user has entered the first number, and thus we can set amt to number. And then we can use -= operator, which basically means:
amt = amt - number;
But before all this, using if (number < 0) break; we can check if the user has entered a negative number, and if the user has entered a negative number, then the break keyword will break out of the while loop.
First of all I am new to C++, can you guys help me with validating if value enter is an integer? And if my while statement in int(main) can be replace with a function.
#include <iostream>
using namespace std;
int validateNumb (int numb, int lim){
//takes a num, limit and checks if number is within limit
while (numb>=lim) { //if outside limit
cout << "Invalit input, try again with number (less than " << lim <<"): ";
cin >> numb; //assign user input value
}
cout << "Your integer is: " << numb << "\n\n"; //display input value
return numb;
}
int main() {
//variables
int num1, num2, num3, sum;
int limnum1, limnum2, limnum3;
//Welcome message
cout << "Hello & Welcome to E&M Ls1\n\n\n";
//First Number
cout << "Please Define the limit for First integer: ";
while (!(cin >> limnum1)) //if input is not true
{
cout << "Error!! Invalit input, please enter the First integer: ";
cin.clear();
cin.ignore(50, '\n');
}
cout << "Please Enter the First Integar that is (less than " << limnum1 << "): ";
while (!(cin >> num1)) //if input is not true
{
cout << "Error!! Invalit input, please enter the First integer: ";
cin.clear();
cin.ignore(50, '\n');
}
num1 = validateNumb(num1, limnum1); //check condition
//Second Number
cout << "Please Define the limit for Second integer: ";
while (!(cin >> limnum2)) //if input is not true
{
cout << "Error!! Invalit input, please enter the Second integer: ";
cin.clear();
cin.ignore(50, '\n');
}
cout << "Please Enter the Second Integar that is (less than " << limnum2 << "): ";
while (!(cin >> num2)) //if input is not true
{
cout << "Error!! Invalit input, please enter the Second integer: ";
cin.clear();
cin.ignore(50, '\n');
}
num2 = validateNumb(num2, limnum2); //check condition
//Third Number
cout << "Please Define the limit for Third integer: ";
while (!(cin >> limnum3)) //if input is not true
{
cout << "Error!! Invalit input, please enter the Third integer: ";
cin.clear();
cin.ignore(50, '\n');
}
cout << "Please Enter the Third Integar that is (less than " << limnum3 << "): ";
while (!(cin >> num3)) //if input is not true
{
cout << "Error!! Invalit input, please enter the Third integer: ";
cin.clear();
cin.ignore(50, '\n');
}
num3 = validateNumb(num3, limnum3); //check condition
//Sum for num1+num2+num3
sum = num1+num2+num3;
cout << "Sum of " << num1 <<" & " << num2 <<" & " << num3 <<" is: " << sum << ""; //display input value
cout<<"_______________________"<<endl;
cout<<"Thank you & Goodbye"<<endl; //end of the program
return 0;
}
bool is_integer(float k)
{
return std::floor(k) == k;
}
This solution should work for all possible values of k. I am pretty sure this is a case where you can safely compare floats using ==.
and yes your main can be broken into functions, maybe something like...
int getFirstNumber(){
int num =0;
// copy your code to get the first number
return num;
}
int getSecondNumber(){
int num =0;
// copy your code to get the second number
return num;
}
int getThirdNumber(){
int num =0;
// copy your code to get the thirdnumber
return num;
}
int sum(int a,int b,int c){
return (a+b+c);
}
int main(){
int a,b,c,d =0;
a = getFirstNumber;
b = getSecondNumber;
c = getThirdNumber;
d = sum(a,b,c);
return 0;
}
EDIT: I see you want to check if the number is in a valid range...
here:
// Returns true if x is in range [low..high], else false
bool inRange(unsigned low, unsigned high, unsigned x)
{
return ((x-low) <= (high-low));
}
hello i want to build a programme that display even and odd numbers from given numbers
i get this message error which is error C2061: syntax error : identifier 'cout'
i try again to look but i cant find any.i search online and says that i should using instead of which i did but it didnt work too. How to solve this
below is my code
#include<stdio.h>
#include <iostream>
using namespace std;
int main(){
int number;
int firstNum,secondNum;
int countOdd,countEven;
cout << "Enter the first number: ";
cin >> firstNum;
cout << "Enter the second number: ";
cin >> secondNum;
if (firstNum>secondNum )
cout << "Sorry the first number must be less than second number";
else if
cout << "Odd numbers in given range are: ";
for(number = firstNum;number <= secondNum; number++)
if(number % 2 !=0)
cout << number<< " ";
countOdd = number;
cout << "\nTotal count of odd number is :" << countOdd << endl;
printf("\nEven numbers in given range are: ");
for(number = firstNum;number <= secondNum; number++)
if(number % 2 ==0)
cout << number << " ";
countEven = number;
cout << "\nTotal count of even number is :" << countEven << endl;
return 0;
}
You have problem with your else statement. here is how you should write it:
else {
cout << "Odd numbers in given range are: ";
for(number = firstNum;number <= secondNum; number++)
if(number % 2 !=0){
cout << number<< " ";
countOdd++;
}
cout << "\nTotal count of odd number is :" << countOdd << endl;
printf("\nEven numbers in given range are: ");
for(number = firstNum;number <= secondNum; number++)
if(number % 2 ==0){
cout << number << " ";
countEven++;
}
cout << "\nTotal count of even number is :" << countEven << endl;
}
also, don't forget to initialize countOdd and countEven to zero at the beginning of your program.
just started reading a C++ book and one of the practice problems was to write a small calculator that takes as input one of the four arithmetic operations, the two arguments to those operations, and then prints out the results.
Sadly, the program works up until the user inputs the arithmetic option.
So if I chose to do multiplication, id write "Multiplication" and it was just stay there and not do anything after.
Image of the problem im having
#include <iostream>
#include <string>
using namespace std;
int main(){
// Simple calculator program
// Declaring three variables
float numberOne;
float numberTwo;
string operationOption;
// Asking the user which two numbers he/she will use
cout << "Enter the first number you would like to apply a arithmetic operation to: ";
cin >> numberOne;
cin.ignore();
cout << "Now enter the second number: ";
cin >> numberTwo;
cin.ignore();
// Using cin to input users selection
cout << "Enter the operation you want to perform." << endl;
cout << "The options you have are: " << endl;
cout << "Multiplication, Subraction, Division and Addition: " << endl;
cin >> operationOption;
cin.ignore();
cin.get();
// Where it all happens
if ( operationOption == "Multiplication" ) {
cout << "The first number multiplied by the second number is: " << numberOne * numberTwo << endl;
} else if ( operationOption == "Division" ) {
cout << "The first number divided by the second number is: " << numberOne / numberTwo << endl;
} else if ( operationOption == "Subtraction" ) {
cout << "The first number subtracted by the second number is: " << numberOne - numberTwo << endl;
} else if ( operationOption == "Addition ") {
cout << "The first number added to the second number is: " << numberOne + numberTwo << endl;
} else {
cout << "You entered an invalid option.";
};
}
Remove line :
cin.get();
will solve your problem
I have a quick question for input verification. I have my loop, and it works for negative numbers, but when I input something like a + sign, it causes an infinite loop. Is there any way to fix it?
cout << "Input Quarter 1 Sales: " << endl;
cin >> quarter1;
while (quarter1 < 0)
{
cout << "Error! Sales Must be a Positive Number!" << endl;
cout << "Please Input a Positive Number" << endl << endl;
cin >> quarter1;
}