Why is not Processing char in switch statement? C++ - c++

I am trying to take and process the user decision by using char +, -, /, *, Why is switch statement ignoring them thus I don't see any mistake in my Code.
#include <iostream>
using namespace std;
void optionMenu();
double UserOutput(int);
int main ()
{
int UserChoice;
optionMenu();
cout << " Choice: ";
cin >> UserChoice;
UserOutput(UserChoice);
return 0;
}
void optionMenu()
{
cout << " Select your choice" << '\n';
cout << " + for Addition" << '\n';
cout << " - for Subtraction" << '\n';
cout << " / for Division" << '\n';
cout << " * for Multiplication" << '\n';
}
double UserOutput (int UserChoice)
{
int value1, value2;
switch (UserChoice)
{
case '+':
cout << " Enter First Number: "; cin >> value1;
cout << " Enter Second Number: "; cin >> value2;
cout << " The result for the Entered numbers is equal to: [" << (value1 + value2) << "]" << '\n';
break;
case '-':
cout << " Enter First Number: "; cin >> value1;
cout << " Enter Second Number: "; cin >> value2;
cout << " The result for the Entered numbers is equal to: [" << value1 - value2 << "]" << '\n';
break;
case '/':
cout << " Enter First Number: "; cin >> value1;
cout << " Enter Second Number: "; cin >> value2;
if(value2)
cout << " The result for the Entered numbers is equal to: [" << value1 / value2 << "]" << '\n';
else
cout << " Not Allowed or Infinity, Try again!" << '\n';
break;
case '*':
cout << " Enter First Number: "; cin >> value1;
cout << " Enter Second Number: "; cin >> value2;
cout << " The result for the Entered numbers is equal to: [" << value1 * value2 << "]" << '\n';
break;
default:
cout << " Invalid Input Try again" << '\n';
break;
}
}

Your issue is right here:
int UserChoice;
optionMenu();
cout << " Choice: ";
cin >> UserChoice;
You're asking the user to enter +,-,/,* characters, but you're reading it into an int variable. This will cause std::cin to fail and 0 to be written into UserChoice (see here for more).
Instead, read that choice in as a char:
char UserChoice;
//^^
optionMenu();
cout << " Choice: ";
cin >> UserChoice;
Note that you also have the following warning:
main.cpp:60:1: warning: no return statement in function returning non-void [-Wreturn-type]
This is because you've specified UserOutput as a function returning a double, but you never return anything. You may want to change this to a void function to avoid mistakes/bugs in the future.

The problem is how you read the users choice:
int UserChoice;
cin >> UserChoice;
This tries to convert an integer in text from from the stream into an int. The stream contains for example "+". The parser sees '+' as next character, which is not a digit, stops and returns 0. The users input is actually never consumed.
To read the users choice you have use
char UserChoice;
PS: double UserOutput (int UserChoice) should be void.

Because you are sending user input in int format to switch statement and it is not possible to convert int to char directly in your case, so the int is ignored and returned the default stream of switch statement.
To solve it just send and take the user input in char and it will work with char.
#include <iostream>
using namespace std;
void optionMenu();
double UserOutput(char);
int main ()
{
char UserChoice;
optionMenu();
cout << " Choice: ";
cin >> UserChoice;
UserOutput(UserChoice);
return 0;
}
void optionMenu()
{
cout << " Select your choice" << '\n';
cout << " + for Addition" << '\n';
cout << " - for Subtraction" << '\n';
cout << " / for Division" << '\n';
cout << " * for Multiplication" << '\n';
}
double UserOutput (char UserChoice)
{
int value1, value2;
switch (UserChoice)
{
case '+':
cout << " Enter First Number: "; cin >> value1;
cout << " Enter Second Number: "; cin >> value2;
cout << " The result for the Entered numbers is equal to: [" << (value1 + value2) << "]" << '\n';
break;
case '-':
cout << " Enter First Number: "; cin >> value1;
cout << " Enter Second Number: "; cin >> value2;
cout << " The result for the Entered numbers is equal to: [" << value1 - value2 << "]" << '\n';
break;
case '/':
cout << " Enter First Number: "; cin >> value1;
cout << " Enter Second Number: "; cin >> value2;
if(value2)
cout << " The result for the Entered numbers is equal to: [" << value1 / value2 << "]" << '\n';
else
cout << " Not Allowed or Infinity, Try again!" << '\n';
break;
case '*':
cout << " Enter First Number: "; cin >> value1;
cout << " Enter Second Number: "; cin >> value2;
cout << " The result for the Entered numbers is equal to: [" << value1 * value2 << "]" << '\n';
break;
default:
cout << " Invalid Input Try again" << '\n';
break;
}
}

Related

C++ switch statement for arithmetic operations

When I run my program, it doesn't allow me to pick an operation. It just goes straight to "Invalid option" and asks again. I want to be able to choose '+', '-', '*', '/', '^', and '!' as my options. What did I do wrong?
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
char operation;
int num1, num2, result, remain;
//Display the menu to the user and get their first choice
cout << "What operation would you like to perform:" << endl
<< " + addition\n - subtraction\n * multiplication\n / division\n ^ number to power\n ! factorial"
<< "\n q quit" << endl << endl << "Operation? ";
cin >> operation;
//Switch - the user does not want to quit
switch (operation)
{
case 1: result=num1+num2;
cout << "Enter the first number to add: " << endl;
cin >> num1;
cout << "Enter the second number to add: " << endl;
cin >> num2;
cout << endl << num1 << " + " << num2 << " = " << result;
break;
case 2: result=num1-num2;
cout << "Enter the first number to subtract: " << endl;
cin >> num1;
cout << "Enter the second number to subtract: " << endl;
cin >> num2;
cout << endl << num1 << " - " << num2 << " = " << result;
break;
case 3: result=num1*num2;
cout << "Enter the first number to multiply: " << endl;
cin >> num1;
cout << "Enter the second number to multiply: " << endl;
cin >> num2;
cout << endl << num1 << " * " << num2 << " = " << result;
break;
case 4: result=num1/num2;
cout << "Enter the dividend: " << endl;
cin >> num1;
cout << "Enter the divisor: " << endl;
cin >> num2;
cout << endl << num1 << " / " << num2 << " = " << result;
cout << endl << num1 << " % " << num2 << " = " << result;
break;
case 5: result=num1^num2;
cout << "Enter the base number " << endl;
cin >> num1;
cout << "Enter the power: " << endl;
cin >> num2;
cout << endl << num1 << " ^ " << num2 << " = " << result;
break;
case 6: result=num1!=num2;
cout << "Enter a number: " << endl;
cin >> num1;
cout << endl << num1 << " ! " << " = " << result;
break;
default:
cout << "That is an invalid operation!" << endl;
break;
} // switch statement closed
cout << endl << "What operation would you like to perform:" << endl << " + addition\n - subtraction\n * multiplication\n / division\n ^ number to power\n ! factorial" << "\n q quit" << endl << endl << "Operation? ";
cin >> operation;
return 0;
} //main statement closed
You are using a char against a switch of ints that do not match character codes that you wish to select. If you would like to decide among characters, use character literals instead of integer numbers:
case '+':
// Read inputs first
cout << "Enter the first number to add: " << endl;
cin >> num1;
cout << "Enter the second number to add: " << endl;
cin >> num2;
// Compute the result next
result=num1+num2;
cout << endl << num1 << " + " << num2 << " = " << result;
break;
Note that the assignment
result=num1+num2;
should come after the code that reads the inputs, i.e. num1 and num2.
at the end when I ask if it wants to do another operation, it just ends even if I pick an operation.
This is because an end-of-line character that you entered after num2 is sitting in the buffer. You need to ignore it. Add this line:
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
before
cin >> operation;

how do you do a integer validation in C++?

ok, I have been looking for days now but I cant find anything that will work.
I have a program and I want to make sure that the user enters a integer and not a double.
this program works fine but I need to validate the numOne and numTwo to make sure they are integers and not doubles, (5.5)
int main()
{ //This is where my variables are stored
int numOne, numTwo, answer, rightAnswer, ranNumOne, ranNumTwo;
//this will display to the user to enter a range of numbers to be used
cout << "Please enter a set of numbers to be the range for the problems." << endl;
cout << "Please enter the beginning number." << endl;
cin >> numOne;
cout << "please enter the ending number." << endl;
cin >> numTwo;
//this makes sure that the user entered a integer(if not the program will close)
if (!(cin >> numOne))
{
cout << "You did not enter a integer PLEASE RE-RUN THE PROGRAM AND TRY AGAIN!" << endl;
cin.clear();
cin.ignore(100, '\n');
exit(0);
}
cout << "please enter the ending number." << endl;
cin >> numTwo;
//this makes sure that the user entered a number(if not the program will close)
if (!(cin >> numTwo))
{
cout << "You did not enter a integer PLEASE RE-RUN THE PROGRAM AND TRY AGAIN!" << endl;
cin.clear();
cin.ignore(100, '\n');
exit(0);
}
//this is where the first number is generated
srand(time(0));
ranNumOne = rand() % (numOne - numTwo) + 1;
system("PAUSE");
//this is where the second number is generated
srand(time(0));
ranNumTwo = rand() % (numOne - numTwo) + 1;
//this is where the calculations are done
rightAnswer = ranNumOne + ranNumTwo;
//this displays the problem that was generated
cout << "What is: " << endl;
cout << setw(11) << ranNumOne << endl;
cout << setw(6) << "+" << setw(3) << ranNumTwo << endl;
cout << " -------\n";
cin >> answer;
//this checks to see if the answer is right or not and displays the result
if (answer == rightAnswer)
{
cout << "Your answer was correct! " << endl;
}
else
cout << "The correct answer is: " << rightAnswer << endl;
return 0;
}
Use std:n:ci.fail() to see if it failed.
int numOne;
cin >> numOne;
if(cin.fail())
cout << "Not a number...")
Maybe even a nice template function.
template<typename T>
T inline input(const std::string &errmsg = "") {
T var;
std::cin >> var;
while (std::cin.fail()) {
std::cin.clear();
std::cin.ignore(256, '\n');
std::cout << errmsg;
std::cin >> var;
}
return var;
}
Or not:
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <string>
#include <ctime>
#define DIFF(n1, n2) (n1 > n2 ? n1 - n2 : n2 - n1)
using namespace std;
int input(const string &firstmsg = "", const string &errmsg = "") {
int var;
std::cout << firstmsg;
std::cin >> var;
while (cin.fail()) {
cin.clear();
cin.ignore(256, '\n');
cout << errmsg;
cin >> var;
}
return var;
}
int main(){
//This is where my variables are stored
int numOne, numTwo, answer, rightAnswer, ranNumOne, ranNumTwo;
//this will display to the user to enter a range of numbers to be used
cout << "Please enter a set of numbers to be the range for the problems." << endl << endl;
numOne = input("Please enter the beginning number: ", "Invalid. Enter again: ");
//this asks the user for the second number
numTwo = input("Please enter the ending number: ", "Invalid. Enter again: ");
//this is where the first number is generated
srand(time(0));
ranNumOne = rand() % (DIFF(numOne, numTwo)) + 1; // ensures it will always be positive
system("PAUSE");
//this is where the second number is generated
srand(time(0));
ranNumTwo = rand() % (DIFF(numOne, numTwo)) + 1;
//this is where the calculations are done
rightAnswer = ranNumOne + ranNumTwo;
//this displays the problem that was generated
cout << "What is: " << endl;
cout << setw(11) << ranNumOne << endl;
cout << setw(6) << "+" << setw(3) << ranNumTwo << endl;
cout << " -------\n";
cin >> answer;
//this checks to see if the answer is right or not and displays the result
if (answer == rightAnswer){
cout << "Your answer was correct! " << endl;
}
else
cout << "The correct answer is: " << rightAnswer << endl;
return 0;
}
why not, get the number into a double and then see if that double is an int. ie
double d;
cin>>d;
if (ceil(d) != d)
cout >> " not an integer";

Break statement is not in loop or switch statement?

I am having trouble with my code, I have read other forums this site about this problem but they don't really relate to my situation. I am new to C++, I barely have about 3 weeks into the course. I do not know why my break statement isn't working, to me it is in the loop. What am I missing?
float a[60][7];
int row;
cout << "How many students would you like to grade?" << endl;
cin >> studentNum;
cout << "Enter grades for the first student" << endl;
row = 0;
n = studentNum - 2;
while (row < studentNum)
{
a[row][0]=k;
a[row][0] = row;
cout << "Enter grade for test 1: ";
cin >> a[row][1];
cout << "Enter grade for test 2: ";
cin >> a[row][2];
cout << "Enter grade for test 3: ";
cin >> a[row][3];
cout << "Enter grade for test 4: ";
cin >> a[row][4];
a[row][5] = (a[row][1] + a[row][2] + a[row][3] + a[row][4]) / 4;
a[row][6] = a[row][1] * 0.2 + a[row][2] * 0.3 + a[row][3] * 0.3 + a[row][4] * 0.2;
row++;
}
if (row == n)
{
cout << "Enter Grades for the last Student" << endl;
cout << "Enter grade for test 1: ";
cin >> a[row][1];
cout << "Enter grade for test 2: ";
cin >> a[row][2];
cout << "Enter grade for test 3: ";
cin >> a[row][3];
cout << "Enter grade for test 4: ";
cin >> a[row][4];
break;
}
else
{
cout << "Enter grades for the next student" << endl;
row = row + 1;
}
cout << "Stdnt" << "\t" << "Grade1" << "\t" << "Grade2" << "\t" << "Grade3" << "\t" << "Grade4" << "\t" << "Avg1" << "\t" << "Avg2" << endl;
printarray(a, studentNum);
cin.get();
return 0;
Something like this?
float a[60][7];
int row = 0;
std::cout << "How many students would you like to grade?" << std::endl;
std::cin >> studentNum;
n = studentNum - 2;
std::cout << "Enter grades for the first student" << std::endl;
while (row <= n)
{
a[row][0] = k;
a[row][0] = row;
std::cout << "Enter grade for test 1: ";
std::cin >> a[row][1];
std::cout << "Enter grade for test 2: ";
std::cin >> a[row][2];
std::cout << "Enter grade for test 3: ";
std::cin >> a[row][3];
std::cout << "Enter grade for test 4: ";
std::cin >> a[row][4];
a[row][5] = (a[row][1] + a[row][2] + a[row][3] + a[row][4]) / 4;
a[row][6] = a[row][1] * 0.2 + a[row][2] * 0.3 + a[row][3] * 0.3 + a[row][4] * 0.2;
if (row==n)
{
std::cout << "Enter Grades for the last Student" << std::endl;
std::cout << "Enter grade for test 1: ";
std::cin >> a[row][1];
std::cout << "Enter grade for test 2: ";
std::cin >> a[row][2];
std::cout << "Enter grade for test 3: ";
std::cin >> a[row][3];
std::cout << "Enter grade for test 4: ";
std::cin >> a[row][4];
}
else
{
std::cout << "Enter grades for the next student" << std::endl;
}
row++;
}
std::cout << "Student" << "\t" << "Grade1" << "\t" << "Grade2" << "\t" << "Grade3" << "\t" << "Grade4" << "\t" << "Avg1" << "\t" << "Avg2" << std::endl;
printarray(a, studentNum);
std::cin.get();
return 0;
P.S. edit with fixed while

How can I avoid bad input from a user?

I am a very newbie programmer, so I don't really know much about writing code to protect the application.. Basically, I created a basicMath.h file and created a do while loop to make a very basic console calculator (only two floats are passed through the functions). I use a series of if and else if statements to determine what the users wants to do. (1.add, 2.subtract, 3.multiply, 4.divide) I used a else { cout << "invalid input" << endl;} to protect against any other values, but then I tried to actually write a letter, and the program entered a infinite loop. Is there anyway to protect against users who accidentally hit a character instead of a number?
`#include <iostream>
#include "basicMath.h"
using namespace std;
char tryAgain = 'y';
float numOne = 0, numTwo = 0;
int options = 0;
int main()
{
cout << "welcome to my calculator program." << endl;
cout << "This will be a basic calculator." << endl;
do{
cout << "What would you like to do?" << endl;
cout << "1. Addition." << endl;
cout << "2. Subtraction." << endl;
cout << "3. Multiplication" << endl;
cout << "4. Division." << endl;
cin >> options;
if (options == 1){
cout << "Enter your first number." << endl;
cin >> numOne;
cout << "Enter your second number." << endl;
cin >> numTwo;
cout << numOne << " + " << numTwo << " = " << add(numOne, numTwo) << endl;
}
else if (options == 2){
cout << "Enter your first number." << endl;
cin >> numOne;
cout << "Enter your second number." << endl;
cin >> numTwo;
cout << numOne << " - " << numTwo << " = " << subtract(numOne, numTwo) << endl;
}
else if (options == 3){
cout << "Enter your first number." << endl;
cin >> numOne;
cout << "Enter your second number." << endl;
cin >> numTwo;
cout << numOne << " * " << numTwo << " = " << multiply(numOne, numTwo) << endl;
}
else if (options == 4){
cout << "Enter your first number." << endl;
cin >> numOne;
cout << "Enter your second number." << endl;
cin >> numTwo;
cout << numOne << " / " << numTwo << " = " << divide(numOne, numTwo) << endl;
}
else {
cout << "Error, invalid option input." << endl;
}
cout << "Would you like to use this calculator again? (y/n)" << endl;
cin >> tryAgain;
}while (tryAgain == 'y');
cout << "Thank you for using my basic calculator!" << endl;
return 0;
}
`
One way would be to use exception handling, but as a newbie you're probably far from learning that.
Instead use the cin.fail() which returns 1 after a bad or unexpected input. Note that you need to clear the "bad" status using cin.clear().
A simple way would be to implement a function:
int GetNumber ()
{
int n;
cin >> n;
while (cin.fail())
{
cin.clear();
cin.ignore();
cout << "Not a valid number. Please reenter: ";
cin >> n;
}
return n;
}
Now in your main function wherever you are taking input, just call GetNumber and store the returned value in your variable. For example, instead of cin >> numOne;, do numOne = GetNumber();
When you input to cin, it is expecting a specific type, such as an integer. If it receives something that it does not expect, such as a letter, it sets a bad flag.
You can usually catch that by looking for fail, and if you find it, flush your input as well as the bad bit (using clear), and try again.
Read a whole line of text first, then convert the line of text to a number and handle any errors in the string-to-number conversion.
Reading a whole line of text from std::cin is done with the std::getline function (not to be confused with the stream's member function):
std::string line;
std::getline(std::cin, line);
if (!std::cin) {
// some catastrophic failure
}
String-to-number conversion is done with std::istringstream (pre-C++11) or with std::stoi (C++11). Here is the pre-C++11 version:
std::istringstream is(line);
int number = 0;
is >> number;
if (!is) {
// line is not a number, e.g. "abc" or "abc123", or the number is too big
// to fit in an int, e.g. "11111111111111111111111111111111111"
} else if (!is.eof()) {
// line is a number, but ends with a non-number, e.g. "123abc",
// whether that's an error depends on your requirements
} else {
// number is OK
}
And here the C++11 version:
try {
std::cout << std::stoi(line) << "\n";
} catch (std::exception const &exc) {
// line is not a number, e.g. "abc" or "abc123", or the number is too big
// to fit in an int, e.g. "11111111111111111111111111111111111"
std::cout << exc.what() << "\n";
}

Line 48 and 62 C++ error Expected unqualified id before if?

I am programming a simple calculator that subtracts adds divides or multiplies depending on whether you type 1 2 3 or 4. I keep getting this error. Keep in mind I am newer to C++. It happens with the IF lines in Mode == 3 and Mode == 4
#include <iostream>
int main(){
using namespace std;
int x;
int y;
int x2;
int y2;
int x3;
int y3;
int x4;
int y4;
int Mode;
cout << "Welcome to Brian's Calculator!";
cout << endl;
cout << "Pick a mode. 1 is Addition. 2 Is Subtraction. 3 is Multiplacation. 4 is Division";
cin >> Mode;
if (Mode==1){
cout << "You chose addition.";
cout << endl;
cout << "Pick a number.";
cout << endl;
cin >> x;
cout << endl;
cout << "Pick another.";
cout << endl;
cin >> y;
cout << "The sum of the numbers you chose are: " << x+y <<".";
return 0;
};
if (Mode==2){
cout << "You chose subtraction.";
cout << endl;
cout << "Pick a number.";
cout << endl;
cin >> x2;
cout << endl;
cout << "Pick another.";
cout << endl;
cin >> y2;
cout << "The difference of the numbers you chose are: " << x2-y2 <<".";}
return 0;
};
if (Mode==3){
cout << "You chose Multiplacation.";
cout << endl;
cout << "Pick a number.";
cout << endl;
cin >> x3;
cout << endl;
cout << "Pick another.";
cout << endl;
cin >> y3;
cout << "The product of the numbers you chose are: " << x3*y3 <<".";
return 0;
};
if (Mode==4){
cout << "You chose Division.";
cout << endl;
cout << "Pick a number.";
cout << endl;
cin >> x4;
cout << endl;
cout << "Pick another.";
cout << endl;
cin >> y4;
cout << "The quotient of the numbers you chose are: " << x4/y4 <<".";
return 0;
};
At this line:
cout << "The difference of the numbers you chose are: " << x2-y2 <<".";}
You have an extra }
PROBLEM: you have two end-braces instead of one:
if (Mode==2){
...
// DELETE THE EXTRANEOUS "}"!
cout << "The difference of the numbers you chose are: " << x2-y2 <<".";}
return 0;
};
SUGGESTED ALTERNATIVE:
if (Mode==2){
...
// DELETE THE EXTRANEOUS "}"!
cout << "The difference of the numbers you chose are: " << x2-y2 <<".";
return 0;
}
EVEN BETTER:
switch (Mode) {
case 1 :
...
break;
case 2 :
...
break;
On this line you have a misplaced }:
cout << "The difference of the numbers you chose are: " << x2-y2 <<".";}
^
when you fix that you will need an extra } after the end of your program to close main as well. Also you do not need a ; after the } when you close the if statements for example:
if (Mode==1){
// code...
};
^