Simple query regarding operators - c++

Hello I'm writing a program which runs a lot of functions that run based on the user inputted menu choice which I will not be including. My question is why is the following code not responding to differences in user input. For example if I enter menu choice 1 or 4 it doesn't matter and will revert to menu choice 1. I know it has something to do with my = or == operators but neither has produced the correct result so im not sure what to do. Please help!
int main() //Handles the if statements concerning the menu of the program
{
int r_identifier[42]; //Variable Declaration
int year_entry[42];
double gpa_entry[42];
string student_name[42];
int index = 0;
int menuchoice; //Variable Declaration
do
{
print_menu(); //Calls function to print menu
get_selection(menuchoice); //Calls function to get the menu selection
if (menuchoice = 1) //Calls the function to input a new user
{
input_new_student(student_name, r_identifier, gpa_entry, index, year_entry);
cout << "\nThe student with R#" << r_identifier[index] << " was created. " << endl;
index++;
}
else if (menuchoice = 2) //Prints all
{
print_all ();
}
else if (menuchoice = 3) //Prints statistics about all students in a particular year
{
int year_view;
print_by_year(student_name, r_identifier, gpa_entry, index, year_entry);
}
else if (menuchoice = 4) //Prints statistics about all entered users
{
print_statistics();
}
else if (menuchoice = 5) //Quits the program
{
cout << "Have a good summer! ";
cout << endl;
}
} while (menuchoice != 5);
return 0;
}

1.'=' is for assignment
Ex: int a=5 assigns 5 to the variable named a.
In ur case...u should change all ur '=' to '=='.
'==' is for comparison.
Ex: if(a==5)cout<<a; will print a only if a equals 5...
2 The variable menuchoice doesnt take a value ...u should not take it as a parameter of the function getselection... Instead u can make it return the choice something like this menuchoice=getselection()
3 Include an else part... it give some more meaning to the whole program instead of do while...Keep it as simple as possible :)

Related

C++ program stuck in an infinite loop

Please note that I am a complete beginner at C++. I'm trying to write a simple program for an ATM and I have to account for all errors. User may use only integers for input so I need to check if input value is indeed an integer, and my program (this one is shortened) works for the most part.
The problem arises when I try to input a string value instead of an integer while choosing an operation. It works with invalid value integers, but with strings it creates an infinite loop until it eventually stops (unless I add system("cls"), then it doesn't even stop), when it should output the same result as it does for invalid integers:
Invalid choice of operation.
Please select an operation:
1 - Balance inquiry
7 - Return card
Enter your choice and press return:
Here is my code:
#include <iostream>
#include <string>
using namespace std;
bool isNumber(string s) //function to determine if input value is int
{
for (int i = 0; i < s.length(); i++)
if (isdigit(s[i]) == false)
return false;
return true;
}
int ReturnCard() //function to determine whether to continue running or end program
{
string rtrn;
cout << "\nDo you wish to continue? \n1 - Yes \n2 - No, return card" << endl;
cin >> rtrn;
if (rtrn == "1" and isNumber(rtrn)) { return false; }
else if (rtrn == "2" and isNumber(rtrn)) { return true; }
else {cout << "Invalid choice." << endl; ReturnCard(); };
return 0;
}
int menu() //function for operation choice and execution
{
int choice;
do
{
cout << "\nPlease select an operation:\n" << endl
<< " 1 - Balance inquiry\n"
<< " 7 - Return card\n"
<< "\nEnter your choice and press return: ";
int balance = 512;
cin >> choice;
if (choice == 1 and isNumber(to_string(choice))) { cout << "Your balance is $" << balance; "\n\n"; }
else if (choice == 7 and isNumber(to_string(choice))) { cout << "Please wait...\nHave a good day." << endl; return 0; }
else { cout << "Invalid choice of operation."; menu(); }
} while (ReturnCard()==false);
cout << "Please wait...\nHave a good day." << endl;
return 0;
}
int main()
{
string choice;
cout << "Insert debit card to get started." << endl;
menu();
return 0;
}
I've tried every possible solution I know, but nothing seems to work.
***There is a different bug, which is that when I get to the "Do you wish to continue?" part and input any invalid value and follow it up with 2 (which is supposed to end the program) after it asks again, it outputs the result for 1 (continue running - menu etc.). I have already emailed my teacher about this and this is not my main question, but I would appreciate any help.
Thank you!
There are a few things mixed up in your code. Always try to compile your code with maximum warnings turned on, e.g., for GCC add at least the -Wall flag.
Then your compiler would warn you of some of the mistakes you made.
First, it seems like you are confusing string choice and int choice. Two different variables in different scopes. The string one is unused and completely redundant. You can delete it and nothing will change.
In menu, you say cin >> choice;, where choice is of type int. The stream operator >> works like this: It will try to read as many characters as it can, such that the characters match the requested type. So this will only read ints.
Then you convert your valid int into a string and call isNumber() - which will alway return true.
So if you wish to read any line of text and handle it, you can use getline():
string inp;
std::getline(std::cin, inp);
if (!isNumber(inp)) {
std::cout << "ERROR\n";
return 1;
}
int choice = std::stoi(inp); // May throw an exception if invalid range
See stoi
Your isNumber() implementation could look like this:
#include <algorithm>
bool is_number(const string &inp) {
return std::all_of(inp.cbegin(), inp.cend(),
[](unsigned char c){ return std::isdigit(c); });
}
If you are into that functional style, like I am ;)
EDIT:
Btw., another bug which the compiler warns about: cout << "Your balance is $" << balance; "\n\n"; - the newlines are separated by ;, so it's a new statement and this does nothing. You probably wanted the << operator instead.
Recursive call bug:
In { cout << "Invalid choice of operation."; menu(); } and same for ReturnCard(), the function calls itself (recursion).
This is not at all what you want! This will start the function over, but once that call has ended, you continue where that call happened.
What you want in menu() is to start the loop over. You can do that with the continue keyword.
You want the same for ReturnCard(). But you need a loop there.
And now, that I read that code, you don't even need to convert the input to an integer. All you do is compare it. So you can simply do:
string inp;
std::getline(std::cin, inp);
if (inp == "1" || inp == "2") {
// good
} else {
// Invalid
}
Unless that is part of your task.
It is always good to save console input in a string variable instead of another
type, e.g. int or double. This avoids trouble with input errors, e.g. if
characters instead of numbers are given by the program user. Afterwards the
string variable could by analyzed for further actions.
Therefore I changed the type of choice from int to string and adopted the
downstream code to it.
Please try the following program and consider my adaptations which are
written as comments starting with tag //CKE:. Thanks.
#include <iostream>
#include <string>
using namespace std;
bool isNumber(const string& s) //function to determine if input value is int
{
for (size_t i = 0; i < s.length(); i++) //CKE: keep same variable type, e.g. unsigned
if (isdigit(s[i]) == false)
return false;
return true;
}
bool ReturnCard() //function to determine whether to continue running or end program
{
string rtrn;
cout << "\nDo you wish to continue? \n1 - Yes \n2 - No, return card" << endl;
cin >> rtrn;
if (rtrn == "1" and isNumber(rtrn)) { return false; }
if (rtrn == "2" and isNumber(rtrn)) { return true; } //CKE: remove redundant else
cout << "Invalid choice." << endl; ReturnCard(); //CKE: remove redundant else + semicolon
return false;
}
int menu() //function for operation choice and execution
{
string choice; //CKE: change variable type here from int to string
do
{
cout << "\nPlease select an operation:\n" << endl
<< " 1 - Balance inquiry\n"
<< " 7 - Return card\n"
<< "\nEnter your choice and press return: ";
int balance = 512;
cin >> choice;
if (choice == "1" and isNumber(choice)) { cout << "Your balance is $" << balance << "\n\n"; } //CKE: semicolon replaced by output stream operator
else if (choice == "7" and isNumber(choice)) { cout << "Please wait...\nHave a good day." << endl; return 0; }
else { cout << "Invalid choice of operation."; } //CKE: remove recursion here as it isn't required
} while (!ReturnCard()); //CKE: negate result of ReturnCard function
cout << "Please wait...\nHave a good day." << endl;
return 0;
}
int main()
{
string choice;
cout << "Insert debit card to get started." << endl;
menu();
return 0;
}

c++ numbering the inputs for simple program

so im new to c++ and im doing a program that takes user inputs for any amount number say 5 so i will get 5 inputs from user and calculate the sum of it ,i did make the program but what i want for the output is say
"Enter Input 1:xx
"Enter Input 2:xx
so on and on as the user input say 5 so it goes on for 5 times however my program takes the user input and i enter it, it dosnt say enter input 1 ,so i want to show the enter input 1 enter 2 part hope someone can help me with this sorry for my poor explanation
#include<iostream>
using namespace std;
int main() {
while (true) {
// prompts the user to ask how many inputs they want
int x;
cout << "Enter input : ";
cin >> x;
// If x = -1 dont repeat the loop
if (x == -1)
break;
// get the input from above and calculate the total of the input
int sum = 0;
for (int i = 0; i < x; i++) {
int value;
cin >> value;
sum += value;
}
// Output the total
cout << "Output total: " << sum << endl;
}
system("pause");
return 0;
}
Okay to start out, there are times when to use break and there are times not to. This scenario is not meant for them. Although, I used one in my code I did it because I am rushing. I would recommend to take the code snippet, learn from it, and see how to optimize it :)
Also, just for future purposes its important to understand your task at hand and be able to communicate it well so others can help debug and answer your question.
Heres what I think your question is:
"I want to make a program in cpp that allows the user to first submit how many numbers they would like to input. From there I would then ask them for the indicated number of inputs. After gathering all inputs I will then add those numbers together and output the sum. If at any point they decide to type in -1, I will stop asking for inputs and give their sum on the spot."
#include<iostream>
using namespace std;
int main() {
bool runProgram = true;
cout << "Hi welcome to my sum calculator program!\n";
cout << "This program will prompt you for a number of inputs and then calculate the total of them.\n";
cout << "If you no longer want to be prompted for numbers at any time type in -1!\n";
cout << "Press enter to begin!\n";
cin.get();
while (runProgram) {
// prompts the user to ask how many inputs they want
int x;
cout << "How many inputs?\n";
cin >> x;
// If x = -1 dont repeat the loop
if (x == -1){
runProgram = false;
}else{
// get the input from above and calculate the total of the input
int sum = 0;
int val = 0;
for (int i = 0; i < x; i++) {
cout<< "Input #" << i+1;
cin >> val;
if(val == -1){
runProgram = false;
break;
}
sum += val;
}
// Output the total
cout << "Your Output total is " << sum << endl;
}
}
system("pause");
return 0;
}

Incremented int is resetting at the end of the function

This is the function in question. The variable in question is count1. Prior to return count1; the function appears to reset count1 to either 1 or 2. The result of the final cout line is n lines where n=number of tries including the correct answer. Each line outputs a number that is 1 higher than the line below until count1 = either 1 or 2. I haven't been able to establish a pattern as to which it will finally output.
The questions themselves are simply placeholders.
What on Earth is going on?
Note: I am a very new programmer, and I am aware that there are likely more efficient ways to do what I am doing that I have not learned. I'm open to suggestions, but my understanding of those suggestions will likely be hampered by my unfamiliarity with C++
int q1(int count1) //q1() is always fed a value of 1.
{
using namespace std;
if (count1 <= 3) //User gets 3 tries to answer for full credit.
{ //count1 is returned in order to determine user score.
cout << "What is 2+2 \n"; //problem appears to occur between here and the end of this if statement.
double a1;
cin >> a1;
if (a1 == 4)
{
cout << "Yup. You know what 2+2 is. \n\n";
}
else
{
wrong(); //wrong() is a single line void function using std::cout and nothing else.
q1(++count1);
}
}
else
{
cout << "You have used all three tries. Next question. \n\n";
++count1; //count1 is incremented for an if statement in int main()
}
cout << count1 << "\n"; //This line is strictly for debugging
return count1;
}
Output of the final cout line looks along the lines of this:
5
4
3
2
Without \n
5432
EDIT:
There was an answer below that is deleted for some reason that appeared to resolve my problem.
The answer stated I should replace q1(++count1) with count1 = q1(++count1);
In my mind this shouldn't work, but in practice it seems to work. Why?
When using recursion, the first time your function runs count1 is 1 (as you said). If the user answers right, then your function will return 1, because the value of count1 never changes.
If the user answers wrong, then count1 increases by 1 and gives it's value to a new function (of the same type). Keep in mind that you pass the value of count1, that means the new function (the second q1()) will get the number 2 but will have a new variable count1. They may have the same name, but they are different variables.
There are two ways to solve your problem:
Either by using pointers, this way you pass the address of count1, and each function changes the same variable. (This is the hardest way and not the most efficient) or
Instead of making recursive calls, you can make a while like so:
int q1(int count1)
{
using namespace std;
while (count1 <= 3) //Run as long as user has chances
{
cout << "What is 2+2 \n";
double a1;
cin >> a1;
if (a1 == 4)
{
cout << "Yup. You know what 2+2 is. \n\n";
//Using `break` you stop the running `while` so the next
//step is for the function to return
break;
}
else
{
wrong();
//By incrementing `count1` the next time the `while` runs
//if user ran out of tries it will not enter the loop, so
//it will return `count1` which would most likely be 4
count1++;
}
}
//Here the function is about to return, so you check if user won or lost
if (count1 == 4)
cout << "You have used all three tries. Next question. \n\n";
//Debug
cout << count1 << "\n";
//Return
return count1;
}

Functions in C++ - The 13 Sone game

I am trying to write a program that requires input validation through functions. The idea behind it is much like the 21 stones only it is with 13 and the computer always wins. The game starts with 13 stones and the computer will always choose 1 on the first turn creating a multiple of 4 scenario. This means if the user takes 3 computer takes 1, user takes 2 computer takes 2 and so on until no stones remain. My problem is I am having a hard time getting my head around functions and how data is called from the parameters within so any help with this would be greatly appreciated!
This is what I have sofar.
#include <iostream>
using namespace std;
//function prototypes
bool validPick(int numStones);
int computerPick(int stones_in_pile, int player2taken);
int playerPick(int stones_in_pile);
int main()
{
int stones_left = 13, P1Taken, P2Taken;
cout << "You have shosen to play the game 13 stones against me, the MIGHTY "
<< "COMPUTER!\nThe object of the game is to take 1, 2 or 3 stones from"
<< " the pile on your turn.\nThe player that removes the last stone "
<< "or stones from the pile wins the game.\nGood Luck... You will need"
<< " it! I NEVER LOOSE!!"
<< endl << endl;
computerPick(stones_left, P2Taken);
playerPick(P1Taken);
validPick(stones_left);
//game logic here -- This is far from done.
stones_left -= P1Taken;
stones_left -= P2Taken;
return 0;
}
/******************************************************************************\
* Validate the picked number 1-3 are only valid numbers to choose from. *
\******************************************************************************/
bool validPick(int numStones)
{
if((numStones < 1) || (numStones >3))
cout << "Invalid Selection. 1-3 is all you can have!";
else
return numStones;
}
/******************************************************************************\
* Computer's function calls. Should start with 1. We always want the computer *
* to win the game. *
\******************************************************************************/
int computerPick(int stones_in_pile, int player2taken)
{
if(player2taken == 0)
stones_in_pile -= 1;
else
{
if(player2taken == 1)
stones_in_pile -= 3;
else
if(player2taken == 2)
stones_in_pile -= 2;
else
stones_in_pile -=1;
}
return stones_in_pile;
}
/******************************************************************************\
* Player's Pick function call goes here. The player goes second *
\******************************************************************************/
int playerPick(int stones_in_pile)
{
cout << "Please choose the ammount of stones. 1-3 only! : ";
cin >> stones_in_pile;
return stones_in_pile;
}
Despite the fact that you should better read a beginners book than trying to understand C++ by asking such questions, I will try to explain what is wrong in your code by an example:
bool validPick(int numStones) {
if((numStones < 1) || (numStones >3))
cout << "Invalid Selection. 1-3 is all you can have!";
else
return numStones;
}
This function is declared to return a bool value. However, if the condition in the if-clause turns out to be true, the function does not return anything, that is a mistake. Second, numStones is an int, so when you return it as a bool it will get converted (from int to bool) which is probably not what you want. Honestly, I didnt even try to understand the logic of your program but a valid version of this function could look like this:
bool validPick(int numStones) {
if((numStones < 1) || (numStones >3)) {
cout << "Invalid Selection. 1-3 is all you can have!";
return false;
}
return true;
}
There are many philosophies with functions that produce values and how those values are passed back.
Functions can pass values back to the caller by either modifying the parameter or by returning a value.
The playerPick function can either modify the passed value (by passing by reference):
void playerPick(int& stones_in_pile)
{
cout << "Please choose the ammount of stones. 1-3 only! : ";
cin >> stones_in_pile;
}
Or by returning a value:
int playerPick(void)
{
// Local variable to temporarily hold a value.
int stones_in_pile = - 1;
cout << "Please choose the ammount of stones. 1-3 only! : ";
cin >> stones_in_pile;
return stones_in_pile;
}
Note that the latter version uses a local, temporary, variable and the compiler will return a copy of the value upon end of the function.
I'm using void in the parameter for emphasis here.

How do I replay my main function? (Read description, hard to word title)

I apologize in advance for the misleading title, I'm not really sure how to phrase my question without more room. I'll start with showing you my main function.
int main() {
int input;
List List;
cout << "Press '1' to add a node" << endl;
cout << "Press '2' to view the list of nodes" << endl;
cin >> input;
if (input == 1) {
List.addNode();
}
else if (input == 2) {
List.PrintList();
}
}
So as you can see by the nature of the main function, the user will want to input more than 1 node ( input 1 ). As it stands now, if I input a node, the program ends. In a perfect program, I would like to be able to allow the user to input as many data points as they would like and also be able to print them out. Both functions are basically useless right now since more than one data point is need as well as the user will want to reprint the points they entered.
With the description out of the way: My question is just how do I get the main function to replay itself? Thanks for any help in advance guys.
What you really want is a shift that happens all the time in computer science. You'll need to rework your code a little, you've effectively out-lived your main function. Time to re-write your code.
int new_function() {
int input;
... // Do the rest of your function here
}
int main() {
int i;
for (i=0; i < XXX; i++) {
new_function();
}
}
Depending on how your program fully develops, you may want to loop in main, or you might want to do the loop in your new function or whatever. That part of your architecture you'll have to decide based on your functionality.
Good luck!
Why not just shove it in a while loop?
int main() {
int input = 0;
List nodeList;
/*Loop till user chooses to exit.*/
while(input != 3)
{
/*Display options for user and take output.*/
cout << "Press '1' to add a node" << endl;
cout << "Press '2' to view the list of nodes" << endl;
cout << "Press '3' to exit" << endl;
cin >> input;
/*Add a node to list.*/
if (input == 1) {
nodeList.addNode();
}
/*Display node list.*/
else if (input == 2) {
nodeList.PrintList();
}
/*Exit program.*/
else if (input == 3) {
return 0;
}
/*Re-prompt user to input again.*/
else {
cout << "Invalid input.. try again." << endl;
}
}
/*Won't reach.*/
return 0;
}
A for loop will repeat as many times as you wish.
int i=0;
for (i=0;i<10;i++){
// do something 10 times
}
A while loop is great too as noted by the other answer.
Use a do-while loop with an additional cout<<"press 3 for exit". Enclose all the couts, if-else in the do-while to be able to loop it until users hits 3. In the while condition , set while(input!=3).