Some code to force a user to enter a choice - c++

I'm quite new to c++ and I need help on some code to force a user to make a choice. The first choice calls back the main function and the second choice calls return 0, else the program isn't suppose to return 0 in the main function on any choice. The choice are Y or y for yes and n or N for no, aside these letters the code is not to accept any letter.
I would appreciate it a lot if I receive a help, Thank you.
#include "person. h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
person persons;
persons. getInfo();
persons.showInfo();
cout << "do you want to continue, type Y or y for yes and n or N for no to exit" << endl;
char choice;
cin >> choice;
if (choice == ("Y"||"y"))
{
int main();
}
if (choice == ("N"||"n"))
{
return 0;
}
else
{
cout << "please make a choice"; cin >> choice;
} /* This is where I would like to iterate in other for the user to make one of the choices provided above */
return 0;
}

You could employ something like:
if(choice == "Y" || choice == "y")
int main();
else
return 0;
So they must put Y or y to continue, and then anything else will terminate the program with return 0;

Related

Whats a good way to get the program to end based on user input?

I did my "Hello World", I'm just getting started on my programming adventure with C++. Here is the first thing I've written, what are some ways to get it to end with user input? I'd like a yes or no option that would terminate the program. Also any feedback is welcome, thank you
#include <iostream>
using namespace std;
void Welcome();
void calculateNum();
void tryAgain();
int main() {
Welcome();
while (true) {
calculateNum();
tryAgain();
}
system("pause");
}
void calculateNum() {
float userNumber;
cin >> userNumber;
for (int i = 100; i >= 1; i--) {
float cNumber = i* userNumber;
cout << i << " >>>>> " << cNumber << endl;
}
}
void Welcome() {
cout << "Welcome \n Enter a number to see the first 100 multiples \n";
}
void tryAgain() {
cout << "Try again? Enter another number... ";
}
Here is one option:
Switch to do ... while loop, with the condition at the end.
Make your tryAgain() function return a boolean and put it in the while condition.
In tryAgain function read input from the user, and compare it to expected answers.
First, lets add a new header for string, it will make some things easier:
#include <string>
Second, lets rebuild the loop:
do {
calculateNum();
} while (tryAgain());
And finally, lets modify the function:
bool tryAgain() {
string answer;
cout << "Try again? (yes / no)\n";
cin >> answer;
if (answer == "yes") return true;
return false;
}
Now, there is a slightly shorter way to write that return, but it might be confusing for new learners:
return answer == "yes";
You don't need the if because == is an operator that returns bool type value.
You can change your calculateNum() in the following way:
Change the return value of your calculateNum() function into bool to indicate whether the program shall continue or stop
read the input into a std::string
check if the string is equal to your exit string like 'q' for quit
3.a in that case, your function returns false to indicate the caller that the program shall stop
3.b otherwise, create a stringstream with your string and read the content of the stream into your float variable and continue as you do like now
In your loop in your main function you break if calculateNum() returned false
Here is a simple solution:
#include <iostream>
// Here are two new Includes!
#include <sstream>
#include <string>
using namespace std;
void Welcome();
// Change return value of calculateNum()
bool calculateNum();
void tryAgain();
int main()
{
Welcome();
while (true)
{
if (!calculateNum())
break;
tryAgain();
}
system("pause");
}
bool calculateNum()
{
//Read input into string
string userInput;
cin >> userInput;
//Check for quit - string - here just simple q
if (userInput == "q")
return false;
//otherwise use a std::stringstream to read the string into a float as done before from cin.
float userNumber;
stringstream ss(userInput);
ss >> userNumber;
//and proces your numbers as before
for (int i = 100; i >= 1; i--)
{
float cNumber = i * userNumber;
cout << i << " >>>>> " << cNumber << endl;
}
return true;
}
void Welcome()
{
cout << "Welcome \n Enter a number to see the first 100 multiples \n";
}
void tryAgain()
{
cout << "Try again? Enter another number... ";
}
Having your users input in a string you can even do further checks like checking if the user entered a valid number, interpret localized numbers like . and , for decimal delimitters depending on your system settings and so on.

If the user enter "q", program quits

I have this C++ code and I am trying to do the following:
Prompt the user to enter "p" to play or "q" to quit, if the user enters anything "p" the program will continue, if the user enters "q" program would just terminate and if they entered an invalid input, it would also terminate. How do I do that?.
Thank you,
Here is the code:
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
int Umain = 0;
double Atemp = 0;
double Utemp = 0;
double Working = 0;
double Total = 0;
char Answer = 'x';
void displayOverview ();
void playOrQuit();
void promptNumber();
int main(){
displayOverview();
playOrQuit();
promptNumber();
return 0;
}
void displayOverview(){
}
void playOrQuit(){
string playOrNot;
cout << "If you want to play please press 'p' for play, and 'q' if you wish to quit\n";
cin >> playOrNot;
if(playOrNot == "p"){
cout << "Awesome, lets start playing !!! \n";
}if(playOrNot == "q"){
cout << "Alright then, see you soon !!\n";
}
}
void promptNumber(){
do{
cout << "Please Enter numbers between 1 and 12: ";
cin >> Umain;
cout << "\n";
for (Utemp = Umain; Utemp > 0; Utemp--)
{
cout << "Please enter a number: ";
cin >> Atemp;
Working = (Working + Atemp);
}
}while (Answer == 'y');
}
Just add a call to exit after you detect 'q' was pressed:
}if(playOrNot == "q"){
cout << "Alright then, see you soon !!\n";
exit(0); // <=== Add this here
Exiting with a 0 traditionally means the program exited in an expected fashion and without any errors.
The usual way to do this kind of thing is to have PlayOrQuit return a bool with true meaning "keep on playing" and false meaning "quit". Use that function to control a loop:
while (PlayOrQuit()) {
// game logic goes here
}
That way you can put any appropriate cleanup code after the game loop instead of having a brute-force exit from down inside the function.
There are a couple of ways you can achieve this.
But I suggest you include the stdlib.h library and use system("exit") right inside your else statements that is meant to exit the program.
Add end(), return 0 or exit(0).
Use u brain like, if you need this then i will remember nearest possible thing you spot from past.
So you never made these kind of mistake.
}if(playOrNot == "q"){
cout << "Alright then, see you soon !!\n";
exit(0);
}

EXC_BAD_ACCESS error with arrays in C++

sorry if this is a stupid question but I'm trying to write a program that compares 7 numbers that a user inputs to 7 numbers that the computer generates(a kind of lottery simulator). However, when i try to input the 7 numbers that the user inputs the program crashes after the second input. Please help, and thanks in advance!
This is the beginning of my main:
#include <iostream>
#include <iomanip>
#include "Implementation.hpp"
using namespace std;
int main()
{
string name;
cout << "What is your name?\n";
getline(cin, name);
while(1 != 0) //I know this will never be true, I'm just doing it
//because the return statement will
{ //end the program anyways if the user inputs 2
int *userNums = new int[7];
int *winningNums = new int[7];
int cont;
int matches;
cout << "LITTLETON CITY LOTTO MODEL\n";
cout << "--------------------------\n";
cout << "1) Play Lotto\n";
cout << "2) Quit Program\n";
cin >> cont;
if(cont == 2)
return 0;
getLottoPicks(&userNums);
And this is the getLottoPicks function:
void getLottoPicks(int *picks[])
{
int numsAdded = 0, choice;
while(numsAdded <= 7)
{
cout << "Please input a valid number as your lotto decision.\n";
cin >> choice;
if(noDuplicates(*picks, choice) == false)
continue;
*picks[numsAdded] = choice;
numsAdded++;
}
}
I'm fairly certain that it is a problem with the pointers that i'm trying to use, but without them I can't actually change the arrays I don't think, and I couldn't get the function to return an array.
If you're using C++, then you're probably better using a std::vector<int>, and passing in the reference to the vector in getLottoPicks.
However, your code should only be passing the int * to the getLottoPicks, and should process < 7 items - it's the classic off-by one.
call to getLottoPicks:
getLottoPicks(userNums);
and the new getLottoPicks code:
void getLottoPicks(int *picks)
{
int numsAdded = 0, choice;
while(numsAdded < 7)
{
cout << "Please input a valid number as your lotto decision.\n";
cin >> choice;
if(noDuplicates(picks, choice) == false)
continue;
picks[numsAdded] = choice;
numsAdded++;
}
}

Getting identifier choice is undefined

I'm working on a calculator console app. I'm a beginner in C++ I want the program to ask a question after I'm done printing the previous result. I get the following error though and I have no idea how to fix it.
identifier "choice" is undefined
Here is my source code:
#include "stdafx.h"
#include <iostream>
int getUserInput() {
std::cout << "Please enter an integer: ";
int value;
std::cin >> value;
return value;
}
int getConversionFormula() {
std::cout << "What do you want to convert? (1 for Meters to feet, 2 for kilometers to miles, 3 for kilagrams to pounds.): ";
int op;
std::cin >> op;
//user might select an invalid operation that isnt there
//Implement a way to avoid this.
return op;
}
int getUserInput2() {
std::cout << "Do you want to convert anything else? (hit 1 for yes, hit 2 for no): ";
int choice; //for the user if they hit yes or no to the question above.
std::cin >> choice;
return choice;
}
int getUserChoice(int choice) {
//If user selects 1 show the converstion formula screen
if (choice == 1)
getConversionFormula();
if (choice == 2)
std::exit;
return -1;
}
int calculateResult(int x, int op) {
//we will use == to compare two variables to see if they are true or not
if (op == 1)
return x * 3.280839895; //meters to feet
if (op == 2)
return x / 1.609344; //km to miles
if (op == 3)
return x * 2.2046; //kg to pounds
return -1; //If the user entered an invalid operation
}
void printResult(int result) {
std::cout << "Your result is: " << result << std::endl;
}
int main()
{
int input1 = getUserInput(); //Gets the users input
int op = getConversionFormula();
int result = calculateResult(input1, op);
printResult(result);
int input2 = getUserInput2(); //Asks the user if they want to convert anything else
int input3 = getUserChoice(input2, choice);
std::cin.clear(); // reset any error flags
std::cin.ignore(32767, '\n'); // ignore any characters in the input buffer until we find an enter character
std::cin.get(); // get one more char from the user
}
Can someone please tell me how I can fix it? I get the error in the main function just to let everyone know.
choice is not declared in main, it's only in getUserInput2, which it returns. getUserChoice doesn't even take two arguments, so just do:
getUserChoice(input2);
You could start chaining your function calls a bit, e.g.: getUserChoice(getUserInput2()); and thus eliminate a few local variables.

C++ How do I use variables from one function to another?

For the record I am completely green in C++ and any other programming language for that matter, so if it's possible I'd be happy if you can answer in a way that I can understand :)
I have been working on a simple rock, paper, scissors game recently where I have 3 basic functions, one for the user, one for the bot, and one that choose which one wins the game.
I know using system("cls") isn't the best way to go, but I'm not planning on using this outside Windows.
The final function results() need to use the variables x and brand from the two previous functions, however I can't seem to find a way to do this. And where people explain it anywhere else, they explain it too advanced for me. Remeber that I don't need to change any of them, I simply have to compare them to determine the winner.
I'll show you my code here so you can see what you are dealing with.
Please give me comments on other things I can improve here.
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
using namespace std;
int bgame(), ugame(), results();
int main()
{
srand(time(NULL));
cout<<"Welcome to RPS!\n" <<"You know what to do.\n" <<"\n[ENTER]";
cin.ignore();
system("cls");
ugame();
return 0;
}
int ugame()
{
int x;
cout<<"Type a number from 1-3: ";
cin>> x;
cin.ignore();
if ( x == 1 )
{
cout<<"\nYou chose rock!\n" <<"\n[ENTER]";
cin.ignore();
bgame();
}
else if ( x == 2)
{
cout<<"\nYou chose paper!\n" <<"\n[ENTER]";
cin.ignore();
bgame();
}
else if ( x == 3 )
{
cout<<"\nYou chose scissors!\n" <<"\n[ENTER]";
cin.ignore();
bgame();
}
else
{
cout<<"\nTry again.\n" <<"\n[ENTER]";
cin.ignore();
ugame();
system("cls");
}
return 0;
}
int bgame()
{
int brand = rand()>>4;
system("cls");
cout<<"The bot will now choose an item.\n" <<"\n" <<"[ENTER]\n";
cin.ignore();
brand = rand() % 3 + 1;
if ( brand == 1)
{
cout<<"\nBot chose rock!";
cin.ignore();
results();
}
else if ( brand == 2 )
{
cout<<"\nBot chose paper!";
cin.ignore();
results();
}
else if ( brand == 3 )
{
cout<<"\nBot chose scissors!";
cin.ignore();
results();
}
else
{
cout<<"\nError.";
cin.ignore();
bgame();
system("cls");
}
return 0;
}
int results()
{
}
you can send "parameters" to a function.
That's create a copy of your variable and you can use it in another function.
You need to specifies it with your function name (that's named prototype) like this :
int results(int x, int brand)
You put a type name and a variable name.
For example this function will take 2 int as parameters.
int results(int x, int brand)
{
// do something with your variables
}
And when you call the function you type:
results(x, brand);
If you want, this link explains it with images and examples and more details: http://www.cplusplus.com/doc/tutorial/functions/
First, learn how to use functions with parameters.
After that, you should be able to do what you want.
As suggested, you only have to do something like this :
declaration :
int bgame(int x){
... what bgame do ...
}
and in ugame :
int ugame(){
int x;
...
cin >> x;
...
bgame(x);
}
Hope this helps.
Use parameters, pass by value. Have parameters in the function header, so you can pass the value into the funcion.
using namespace std;
int bgame(int x_p), ugame(), results(int x_p, int brand_p);
int main()
{
srand(time(NULL));
cout<<"Welcome to RPS!\n" <<"You know what to do.\n" <<"\n[ENTER]";
cin.ignore();
system("cls");
ugame();
return 0;
}
int ugame()
{
int x;
cout<<"Type a number from 1-3: ";
cin>> x;
cin.ignore();
if ( x == 1 )
{
cout<<"\nYou chose rock!\n" <<"\n[ENTER]";
cin.ignore();
bgame(x);
}
else if ( x == 2)
{
cout<<"\nYou chose paper!\n" <<"\n[ENTER]";
cin.ignore();
bgame(x);
}
else if ( x == 3 )
{
cout<<"\nYou chose scissors!\n" <<"\n[ENTER]";
cin.ignore();
bgame(x);
}
else
{
cout<<"\nTry again.\n" <<"\n[ENTER]";
cin.ignore();
ugame();
system("cls");
}
return 0;
}
int bgame(int x_p)
{
int brand = rand()>>4;
system("cls");
cout<<"The bot will now choose an item.\n" <<"\n" <<"[ENTER]\n";
cin.ignore();
brand = rand() % 3 + 1;
if ( brand == 1)
{
cout<<"\nBot chose rock!";
cin.ignore();
results(x_p, brand);
}
else if ( brand == 2 )
{
cout<<"\nBot chose paper!";
cin.ignore();
results(x_p, brand);
}
else if ( brand == 3 )
{
cout<<"\nBot chose scissors!";
cin.ignore();
results();
}
else
{
cout<<"\nError.";
cin.ignore();
bgame(x_p);
system("cls");
}
return 0;
}
int results(int x_p, int brand_p)
{
// Do whatever you want to do with x (x_p) and brand (brand_p).
}
For you, you only need to return 1 value for each function, so return would work. Instead of return 0;, use return x; and return brand;. In the comparing function, define two new variables, such as y; or crand;, then assign them like this: y=int ugame(); and crand=int bgame();. Then y=x and crand=brand and you can work from there. So then you don't need any parameters or anything. Also, don't try to define brand straight out, just declare int brand; and let the randomizing function (which must be seeded with srand by the way) assign a value to brand. You also don't have to define the functions as int; they will define themselves.