How to use character value in if condition (c++) - c++

{
cout << "type 3 to add ,type 1 to multiply,type division to divide,type 2 to subtract" << endl;
cin >> function;
if (function == 1)
{
multiply();
}
else if (function == 2)
{
subtract();
}
else if (function == 3)
{
add();
}
else if (function == 4)
{
division();
}
cout << "press x to quit or anything else to restart " << endl;
cin >> input;
} while (input !='x');
system("pause");
return 0;
}
in this code i am unable to have a character value with if
eg-if (function=='add') it does not work
if I use if(function='add') everything inside is skipped to the last cout which says
press x to quit or anything else to restart

'add' is a multicharacter literal and is an int type (note the single quotation characters). You almost certainly don't want to do that as then you're in the murky waters of implementation-defined behaviour.
If you want to be able to read in strings then why not use a std::string as the type for function, and use if (function == "add") &c. ? You can even retain your notation cin >> function!

As suggested by Bathsheba, you could implement this functionality with std::string. Bellow you have an example of how you could do this.
#include <iostream>
#include <string>
void multiply() {
std::cout << "multiplication called" << std::endl;
}
void add() {
std::cout << "add called" << std::endl;
}
void subtract() {
std::cout << "substract called" << std::endl;
}
void division() {
std::cout << "division called" << std::endl;
}
int main()
{
using namespace std;
string input;
do {
cout << "type add, multiply, division, or subtract" << endl;
cin >> input;
if (input == "multiply") {
multiply();
}
else if (input == "substract") {
subtract();
}
else if (input == "add") {
add();
}
else if (input == "division") {
division();
}
else {
cout << "You inputed: " << input << endl;
cout << "Command not recognized, please try again" << endl;
continue;
}
cout << "press x to quit or anything else to restart ";
cin >> input;
} while (input != "x");
return 0;
}

Related

Repeat checker goes back to menu even after entering N to input

The goal is to create a five-in-one program for various math stuff. The individual blocks work. After selecting and using a block, the program should then send a prompt asking the user whether to go back to the menu or terminate the program, this also works.
However, the function which checks whether you've inputted "Y", "y", "N", or "n" does not work. Instead, it automatically returns you to the main menu even after inputting "N" or "n", which should terminate the program.
#include <iostream>
#include<cctype>
#include<cstdlib>
#include <ctime>
#include <bits/stdc++.h>
using namespace std;
bool Primecheck(int x){
// checks if prime is positive or nah
if (x <= 1)
return false;
// Check from 2 to n-1
for (int i = 2; i < x; i++)
if (x % i == 0)
return false;
return true;
}
void Repeatcheck(char repeat){
//checks whether you inputted anything other than Y, y, N, or n
while (repeat != 'Y' && repeat != 'y' && repeat != 'N' && repeat != 'n' ){
system("cls");
std::cout << "that's not an option, dumbass." << std::endl;
std::cout << "\n Return to main menu? Y/N" << std::endl;
cin >> repeat;
}
}
int main()
{
//Option selection
int OptSel;
//repeat selection
char repeat;
repeat = 'Y';
//Optsel 1
int prime, i, primed2=0, flag=0;
//Optsel 2
int j,rows;
//Optsel 3
int t1 = 0, t2 = 1, nextTerm = 0;
//Optsel 4
int factorialinput;
long factorial = 1.0;
do{
system("cls");
repeat = 'Y';
startoptsel:
std::cout << "\n----MATHS PROGRAM----" << std::endl;
std::cout << "\n wats poppin?" << std::endl;
std::cout << "1.) prime number checker" << std::endl;
std::cout << "2.) right triangle drawer" << std::endl;
std::cout << "3.) fibonacci" << std::endl;
std::cout << "4.) factorial" << std::endl;
std::cout << "5.) exit" << std::endl;
std::cin >> OptSel;
//check whether option seleccted is available.
if (!std::cin || OptSel <= 0 || OptSel > 5) {
system("cls");
std::cin.clear();
std::cin.ignore(1000, '\n');
std::cout << "\nThat's not an option, dumbass." << std::endl;
std::cout << "\nInput numbers from 1-5." << std::endl;
goto startoptsel;
}
if (OptSel == 1) {
system("cls");
primechecker:
std::cout << "\n----Prime number checker----" << std::endl;
std::cout << "Enter number: " << std::endl;
std::cin >> prime;
// auto filters everything as not prime below 1
primed2=prime/2;
for(i = 2; i <= primed2; i++){
if(prime % i == 0)
{
cout << "\n " << prime << " is not a prime."<<endl;
flag=1;
break;
}
}
if (flag==0)
cout << "\n " << prime << " is a prime."<<endl;
if (!cin) {
system("cls");
std::cin.clear();
std::cin.ignore(1000, '\n');
std::cout << "please input a number" << std::endl;
goto primechecker;
}
std::cout << "\n Return to main menu? Y/N" << std::endl;
cin>>repeat;
Repeatcheck(repeat);
}
if (OptSel == 2) {
system("cls");
triangledrawer:
cout << "\n----RIGHT TRIANGLE DRAWER----" << std::endl;
cout << "\nInput number of rows: ";
cin >> rows;
for(i=1;i<=rows;i++){
for(j=1;j<=i;j++)
cout<< ' ' << j;
cout<<endl;
}
if (!cin) {
system("cls");
std::cin.clear();
std::cin.ignore(1000, '\n');
std::cout << "please input a number" << std::endl;
goto triangledrawer;
}
std::cout << "\n Return to main menu? Y/N" << std::endl;
cin>>repeat;
Repeatcheck(repeat);
}
if (OptSel == 3){
system("cls");
fibonacciprinter:
cout << "\n----Fibonacci printer----";
cout << "\nEnter the number of terms: ";
cin >> prime;
cout << "Fibonacci Series: ";
for (int i = 1; i <= prime; ++i) {
// Prints the first two terms.
if(i == 1) {
cout << t1 << ", ";
continue;
}
if(i == 2) {
cout << t2 << ", ";
continue;
}
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
cout << nextTerm << ", ";
}
if (!cin) {
system("cls");
std::cin.clear();
std::cin.ignore(1000, '\n');
std::cout << "please input a number" << std::endl;
goto fibonacciprinter;
}
std::cout << "\n Return to main menu? Y/N" << std::endl;
cin>>repeat;
Repeatcheck(repeat);
}
if (OptSel == 4){
system("cls");
cout << "Enter a positive integer: ";
cin >> factorialinput;
cout << "Factorial of ";
if (factorialinput < 0)
cout << "Error! Factorial of a negative number doesn't exist.";
else {
for(int i = 1; i <= factorialinput; ++i) {
cout << i << " ";
factorial *= i;
}
cout << "= " << factorial;
}
std::cout << "\n Return to main menu? Y/N" << std::endl;
cin>>repeat;
Repeatcheck(repeat);
repeat = repeat;
}
if (repeat == 'n' || repeat == 'N'){
system("cls");
std::cout << "\nJob done? JOB DONE! Aight wrap it up lesgo." << std::endl;
return 0;
}
}while (OptSel != 5);
system("cls");
std::cout << "\nJob done? JOB DONE! Aight wrap it up lesgo." << std::endl;
return 0;
}
Rewriting the program to instead run when repeat = Y or y and removing the specific instance of terminating the program when N or n is entered instead results in the program terminating automatically no matter what is inputted when the Repeatcheck function is called.
#include <iostream>
#include<cctype>
#include<cstdlib>
#include <ctime>
#include <bits/stdc++.h>
using namespace std;
bool Primecheck(int x){
...
}
void Repeatcheck(char repeat){
while (repeat != 'Y' && repeat != 'y' && repeat != 'N' && repeat != 'n' ){
system("cls");
std::cout << "that's not an option, dumbass." << std::endl;
std::cout << "\n Return to main menu? Y/N" << std::endl;
cin >> repeat;
}
}
int main()
{
...
do{
...
}while (OptSel != 5 && repeat == 'Y' || repeat == 'y');
system("cls");
std::cout << "\nJob done? JOB DONE! Aight wrap it up lesgo." << std::endl;
return 0;
}

Do-While Loop in Functions

I am just studying so don't judge me hard please.
I have a problem. I know how to do a do-while loop. But today I have learned about functions. So I made do-while loops in functions and they are looping infinitely. How do I stop the loops?
#include <iostream>
using namespace std;
void text()
{
cout << "Log in to see the Menu. " << endl;
}
void lg()
{
const string login = "el1oz";
string input;
cout << "Login > " << flush;
cin >> input;
do{
if(login == input){
break;
}
else{
cout << "Try again." << endl;
}
}while(true);
cout << "Correct Login! " << endl;
}
void pw()
{
const string password = "Mau01171995";
string input1;
cout << "Password > " << flush;
cin >> input1;
do{
if(password == input1){
break;
}
else{
cout << "Try again. " << endl;
}
}while(true);
cout << "Correct Passsword! " << endl;
}
int main()
{
text();
lg();
pw();
return 0;
}
You're not changing input after the code enters in the loop. You should put the cin >> input inside the loop.
Also consider when to use a while loop vs a do while loop. In this case a while loop is better.
You probably should not use using namespace std; (More information here).
You should use more descriptive names.
#include <iostream>
using std::cin;
using std::string;
using std::cout;
using std::flush;
using std::endl;
void printWelcome()
{
cout << "Log in to see the Menu. " << endl;
}
void inputUser()
{
const string login = "el1oz";
string input;
cout << "Login > " << flush;
while(cin >> input){
if(login == input){
break;
}
else{
cout << "Try again." << endl;
}
}
cout << "Correct Login! " << endl;
}
void inputPassword()
{
const string password = "Mau01171995";
string input;
cout << "Password > " << flush;
while(cin >> input){
if(password == input){
break;
}
else{
cout << "Try again. " << endl;
}
}
cout << "Correct Passsword! " << endl;
}
int main()
{
printWelcome();
inputUser();
inputPpassword();
return 0;
}

Program flow not affected by forward declaration

Here is the example of my forward declaration code which is not working:
void Register();
void Menu();
void Register() {
string username, password, hospitalname;
ofstream file;
file.open("Hospital Creds.txt");
cout << "Hospital Name: ";
cin >> hospitalname;
cout << "Username: ";
cin >> username;
cout << "Password: ";
cin >> password;
cout << endl;
file << hospitalname << endl;
file << username << endl;
file << password << endl;
system("pause");
system("cls");
Menu();
}
void Menu() {
int choice;
cout << " 1. Register Hospital " << endl;
cout << " 2. Register Donor " << endl;
cout << " 3. Exit " << endl;
cout << endl;
cout << "Please enter a number of your choice: ";
cin >> choice;
switch(choice) {
case 1:
system("cls");
Register();
break;
}
}
void main() {
Menu();
}
It's like this, when the program runs, it goes to the Menu(), then when selected, it goes to Register(), but when it wanna call back the function Menu(), the program exited. What's wrong with it?
If you call Menu() from Register(), the calling chain is never ending. The function are nested too deep. You're soon blowing up the call stack.
In practice, when I write a menu system, I never call previous-level functions from any function. Instead I use a loop to run the main menu infinitely, so I can keep my function call relationship like a tree.
void Sub1() {
// Prompt for input
if (option == 0) {
return; // End the call tree
}
else if (option == 1) {
Sub11();
}
else if (option == 2) {
Sub12();
}
...
}
int MainMenu() {
// Prompt for input
if (option == 0) {
return 0; // Quit program
}
else if (option == 1) {
Sub1();
}
else if (option == 2) {
Sub2();
}
}
....
int main() {
while (MainMenu() != 0);
}
Here's a sample project that I wrote. Note how I arranged the main() function.

C++ : How to assign the same input to a string and an integer in 2 lines?

I'm a very beginner in C++ and I'm actually following the Google tutorial.
Trying to go a little further with the second example, here is my problematic : checking if the input is a number and, if not, being able to restate it in the error message.
Here is a way I used to solve that but the code length tells me that there is a shorter way :
#include <cstddef>
#include <iomanip>
#include <iostream>
#include <stdlib.h>
using namespace std;
bool IsInteger(string str) {
size_t non_num_position = str.find_first_not_of("0123456789-");
size_t sign_position = str.find_first_of("-", 1);
if (non_num_position == string::npos && sign_position == string::npos) {
return true;
}
return false;
}
void Guess() {
int input_number = 0;
string input_string;
do {
cout << "Try to guess the number between 0 and 100 (type -1 to quit) : ";
cin >> input_string;
if (!IsInteger(input_string)) {
int input_string_length = input_string.size();
cout << "Sorry but « " << input_string << " » is not a number." << endl;
cin.clear();
cin.ignore(input_string_length, '\n');
continue;
}
input_number = atoi(input_string.c_str());
if (input_number != -1) {
cout << "You chose " << input_number << endl;
}
} while (input_number != -1);
cout << "The End." << endl;
}
int main() {
Guess();
return 0;
}
Here is the shorter way I try to follow but cin seems to be "emptied" once assigned to input_number (because of the bitwise operator ?) :
void Guess() {
int input_number = 0;
string input_string;
do {
cout << "Try to guess the number between 0 and 100 (type -1 to quit) : ";
if (!(cin >> input_number)) {
getline(cin, input_string);
cout << "Sorry but " << input_string << " is not a number." << endl;
cin.clear();
cin.ignore(100, '\n');
continue;
}
if (input_number != -1) {
cout << "You chose " << input_number << endl;
}
} while (input_number != -1);
cout << "The End." << endl;
}
SOLUTION :
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
void Guess() {
int input_number = 0;
string input_string;
do {
cout << "Try to guess the number between 0 and 100 (type -1 to quit) : ";
cin >> input_string;
try {
input_number = stoi(input_string);
if (input_number != -1) {
cout << "You chose " << input_number << endl;
}
}
catch (const exception&) {
cout << "Sorry but " << input_string << " is not a number." << endl;
}
} while (input_number != -1);
cout << "The End." << endl;
}
int main() {
Guess();
return 0;
}
The problem with your first attempt is that IsInteger is unnecessarily complicated and long. Otherwise, you had the right idea. Your second attempt is much less correct.... once you read from cin, the data is gone. So, as in the first attempt, you need to store the data in a string.
Here's an example which is a little shorter and doesn't need IsInteger at all:
size_t p = 0;
int input_number = std::stoi(input_string, &p);
if (p < input_string.length())
{
cout << "Sorry but " << input_string << " is not a number." << endl;
conitnue;
}
stoi's second argument tells you where the conversion to integer stopped working. So if there was non-int data in the string (such as '123abc') then p will be somewhere before the end of the string. If p is at the end, then the whole string must have been a number.

Unintialized local variable 'e' used

I have this code. It should work perfectly. It's a circle calculator; I'm doing is as an exercise. I want the user to have the option to return the the 'main menu.' I made a yes/no prompt using char* e; but it's uninitialized. How can I initialize
#include <iostream>
using namespace std;
class Circlecalc {
public:
double const pi = 3.1415962543;
double diameter;
double radius;
double circumference;
};
int _welcome() {
Circlecalc calc;
cout << endl;
int i = 0;
char* e;
cin >> i;
while (i != 5)
{
switch (i) {
case(1) :
cout << "Enter your radius." << endl;
cin >> calc.radius;
cout << endl;
cout << (calc.radius * 2) * calc.pi << endl;
cout << "Exit? [Y/N]" << endl;
cin >> e;
if (e == "Y") {
_welcome();
}
else if (e == "N") {
}
else {
cerr << "Unsupported function" << endl;
}
case(2) :
cout << "Enter your diameter" << endl;
cin >> calc.diameter;
cout << endl;
cout << (calc.diameter * 2) * calc.pi << endl;
cout << "Exit? [Y/N]" << endl;
cin >> e;
if (e == "Y") {
_welcome();
}
else if (e == "N") {
}
else {
cerr << "Unsupported function" << endl;
}
break;
case(3) :
cout << "Enter the circumference" << endl;
cin >> calc.circumference;
cout << endl;
cout << (calc.circumference / 2) / calc.pi;
cout << "Exit? [Y/N]" << endl;
cin >> e;
if (e == "Y") {
_welcome();
}
else if (e == "N") {
}
else {
cerr << "Unsupported function" << endl;
}
break;
case(4) :
cout << "Enter the circumference" << endl;
cin >> calc.circumference;
cout << endl;
cout << calc.circumference / calc.pi;
cout << "Exit? [Y/N]" << endl;
cin >> e;
if (e == "Y") {
_welcome();
}
else if (e == "N") {
}
else {
cerr << "Unsupported function" << endl;
}
break;
case(5) :
return(0);
break;
default:
cerr << "Unsupported function." << endl;
}
}
}
Instead of:
char* e;
use:
std::string e;
The reason you get:
Unintialized local variable 'e' used
is that e is not set when passed to operator>> that is used by cin, to initialize it assign an array to it, ie:
char arr[128] = {0};
char* e = arr;
operator>> for cin stream expect that you have provided some memory buffer where read string is located, char* e; is not bound to any such buffer, and that would end in (possibly) crash (Undefined Behaviour).
In this case you do not need to. If you only want a single letter input from the user just use a char like
char response;
Then you would compare it against a character literal instead of a string literal like
if (response == 'N' || response == 'n')
If you want to compare against a string like "no" or "No" then I suggest you use a std::string and not worry about having to allocate memory for the string.