Need help to stop program terminating without users consent - c++

The following code is supposed to do as follows:
create list specified by the user
ask user to input number
3.a) if number is on the list , display number * 2, go back to step 2
3.b) if number isn't on the list, terminate program
HOWEVER step 3.a) will also terminate the program, which is defeating the purpose of the while loop.
here is the code :
#include <iostream>
#include <array>
using namespace std;
int main()
{
cout << "First we will make a list" << endl;
array <int, 5>list;
int x, number;
bool isinlist = true;
cout << "Enter list of 5 numbers." << endl;
for (x = 0; x <= 4; x++)
{
cin >> list[x];
}
while (isinlist == true)
{
cout << "now enter a number on the list to double" << endl;
cin >> number;
for (x = 0; x <= 4; x++)
{
if (number == list[x])
{
cout << "The number is in the list. Double " << number << " is " << number * 2 << endl;
}
else
isinlist = false;
}
}
return 0;
}
Please can someone help me to resolve this ?

I would suggest that you encapsulate the functionality of step 3 into a separate function. You could define a function as follows, and then call it at an appropriate location in the main function.
void CheckVector(vector<int> yourlist)
{
.... // Take user input for number to search for
.... // The logic of searching for number.
if (number exists)
{
// cout twice the number
// return CheckVector(yourlist)
}
else
return;
}
The same functionality can be implemented with a goto statement, avoiding the need for a function. However, using goto is considered bad practice and I won't recommend it.

Your issue is that you set isinlist to false as soon as one single value in the list is not equal to the user input.
You should set isinlist to false ay the beginning of your while loop and change it to true if you find a match.
Stepping your code with a debugger should help you understand the issue. I encourage you to try it.

Related

Code gives desired output but keeps on running

This code I wrote is supposed to subtract one from the number inputed, or divide by 2 based on whether it is a multiple of 3 or not. However, every time I try to run the code, It outputs the numbers I want but then doesn't stop running. I am new to coding and not sure how to fix this.
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main() {
int n;
cout << "Enter a positive number: " << endl;
cin >> n;
if (n < 0) {
cout << "Invalid input." << endl;
}
while (n >= 1) {
if (n % 3 == 0) {
n = n-1;
cout << n << endl;
}
else if (n % 3 != 0) {
n = n / 2;
cout << n << endl;
}
}
return 0;
}
This is a screenshot of the output I get. Instead of giving me the opportunity to run the code again it just stays like this:
I may be misunderstanding what you're asking, however, traversing through the code you can identify that nothing is being done to make the code run again. You would need add what you have inside another while loop. This new while loop would be something like while (input != 0) then run everything you have. In your input statement you could say "Please enter a positive number or enter 0 to exit". This is just an example of an approach, but the premise is that you need something to keep this loop running.

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;
}

I think I'm trying to pass data wrong in my variables? Novice coder inside

I started learning some basics of C++ and I wanted to write some code to practices what I've learned. I wanted to make a class and some functions. It's supposed to be a title screen to start a text game, except there is no game...yet :P
Whenever I enter 1 to start so it displays "Good Work" it just does nothing after I hit enter.
Any point in the right direction would be great. I've been watching videos and reading tutorials on functions, it doesn't seem to cover the problem I'm having...
#include <iostream>
#include <string>
using namespace std;
//Function Protos
void keyError();
int userInput(int x);
//class library
class Title
{
bool nSelect;
int x;
public:
void titleScreen()
{
while(nSelect)
{
cout << "Welcome to Biggs RPG!" << endl << "1. Play 2. Exit" << endl;
userInput(x);
if (userInput(1))
nSelect = 0;
else if (userInput(2))
{
cout << "Closing program..." <<endl;
nSelect = 0;
}
else
keyError();
}
}
};
int main()
{
Title displayTitle;
displayTitle.titleScreen();
cout << "Good work";
return 0;
}
void keyError()
{
cout << "Meow? Wrong input try again." << endl;
}
int userInput(int x)
{
x = 0;
cin >> x;
return x;
}
There are numerous stylistic and technical problems. Try learning from resources recommended in The Definitive C++ Book Guide and List.
Here is a start…
#include <iostream>
#include <string>
// "using namespace std;" is poor practice. Better to write out std::
/* Unless you will have two title screens at the same time,
this should probably be a namespace, not a "singleton" class. */
namespace Title
{
int nSelect;
void titleScreen()
{
do {
// prompt for input
std::cout << "Welcome to Biggs RPG!\n" "1. Play 2. Exit\n";
// get ready to accept input, even if there was an error before
if ( ! std::cin ) {
std::cin.clear(); // tell iostream we're recovering from an error
std::cin.ignore( 1000, '\n' ); // ignore error-causing input
}
// repeat if invalid input
} while( ! std::cin >> nSelect || ! handleInput( nSelect ) );
The difference is that you want to ask for input, then handle it. The code you posted asks for input again each time it checks what the input was.
This is a do … while loop, so it executes at least once and then repeats as long as the condition at the end is true. If the user gives an invalid input, then ! std::cin evaluates to true. Then the policy of C++ is to stop returning any input until you call std::cin.clear(), which signals that you are going to try again. ignore then gets rid of the invalid input. Then ! std::cin >> nSelect tries to read a number, and if that operation is successful, call handleInput (which you must write) which should return false if the input was invalid. So if reading a number fails, or the wrong number was entered, the loop goes again.
You should compare the return value of userInput with 1 or 2, like this:
int userInput(void);
//class library
class Title
{
bool nSelect;
int x;
public:
void titleScreen()
{
nSelect = true;
while(nSelect)
{
cout << "Welcome to Biggs RPG!" << endl << "1. Play 2. Exit" << endl;
x = userInput();
if (x == 1)
nSelect = false;
else if (x == 2)
{
cout << "Closing program..." <<endl;
nSelect = false;
}
else
keyError();
}
}
};
and define userInput as:
int userInput(void)
{
int x = 0;
cin >> x;
return x;
}
I sense confusion about the difference between parameters and return values. When you define a function as
int userInput(int x) {
...
You pass a value to the function (x) and return a value with the return statement. In your case you don't need to pass a parameter to your function; you need to return a value. You access this value by assigning it to another variable:
theResult = userInput(123);
But it doesn't matter what value you pass to the function; you might as well use
int userInput(void) {
...
In which case you can use
theResult = userInput();
Now just to confuse you, it is possible to pass the address of a variable as a parameter to a function. You can use that either to access data (usually a "larger" block of data like an array or struct) but it can also be used to provide a place where a return value is stored. Thus
void squareMe(int *x){
*x*=*x;
}
Would return the square of the number pointed to in that location. You could then do
int x=4;
squareMe(&x);
cout << x;
Would print out 16 (!). This is because the function looks at the contents of the address (&x is the address of the variable x), and multiplies it by itself in- place.
I hope this explanation helps.

while loop, really don't understand

hi im trying to do a while loop, im new to programming and reading online i cant really get my head around it, i have used flag to show that the inputted name matches the name in the data file, i want to do this so that after i know it doesnt match it loops it the whole thing again, i have no clue how to implement this,
{
clrscr();
cout << "This Is The Option To Delete A Record\n";
char yesno;
char search;
char name[21];
int flag = 0;
cout << "Enter Employee Name : ";
Input(name,20);
for (int r=0;r<row;r++)
{
if( strnicmp(name, emp[r].first_name, strlen(name) ) == 0 )
{
flag = 1;
clrscr();
cout << "Employee Number - " << emp[r].employee_number << endl;
cout << "Name - " << emp[r].first_name << " " << emp[r].surname << endl;
cout << "Department Number - " << emp[r].department_number << endl;
cout << "Week Ending Date - " << emp[r].weekend << endl;
cout << "Delete This Record (Y/N)? : ";
Input(yesno);
yesno = tolower(yesno);
if ( yesno == 'y' )
{
emp[r].deleted = true;
cout << "Record Has Been Deleted";
}
else if ( yesno == 'n')
{
cout << "Record Hasn't Been Deleted";
}
}
}
if (flag == 0)
{
cout << "There Are No Matching Records" << endl;
}
pressKey();
}
It's pretty simple, so have a bunch of code you want to keep executing it while a flag is zero, so that's just
int flag = 0;
while (flag == 0)
{
// whole bunch of code
}
That's it, just replace 'whole bunch of code' with the code you've written above.
Implementing this in a while loop would look like this:
bool flag=false;
while(!flag){
...
if(<find a match>) flag=true;
}
Assuming you understand the for loop, I think you can understand the while loop quite easily based on the comparison of for and while.
See, you used a for loop:
for (int r=0;r<row;r++){
// do stuff
}
There are 3 key points here.
int r=0 This is your initial condition.
r<row This is your condition which keeps the loop running.
r++ This is what happens at the end of each iteration of loop.
To rephrase the statements above:
Considering r equals zero initially, while r is less than row, increment r.
Now we can easily see how while loop is striking us:) To implement this, consider the following while loop example:
int r=0; //(1)
while(r<row){ //(2)
//do stuff
r++; //(3)
}
See, now the 2 loops do practically the same thing.
If you want to do operations based on a flag, you can also prefer an infinite loop:
while(1==1){
if(some condition)
break;
}
as well as an infinite for loop:
for(;;){
if(if some condition)
break;
}
Again, 2 loops are practically the same.
so basically, you have a file with some data. And also, you accept some data from the user.
And then you perform a comparison between the appropriate fields of the two sets.
Why would you want to do it all over again once the entire comparison (file process) is done?
if you simply want to run an infinite loop, you can do this:
while(true)
{
//your code
}
you can do same with a for loop also. infact for loop and while loop both are same except for the syntax. i.e. an infinite for loop.
for (int r=0;r<row;r++)
{
if(r==row-1)
{
r=0;
}
}
I guess what you want to do is to, once one set of user input doesn't match the file content, you want to take another set and match it again and so on.
so you don't need an infinite or always executing loop for this.
Just make your comparison module a separate function which should accept the set of user inputs. All you do is accept user inputs and show the result. And give the user an option to re-enter inputs.
Below is simple algo for what you want.
int main()
{
char a='a';
while(a != '~')
{
TakeUserInput();
if(PerformComparison())
{
cout << "Success";
break;
}
}
}
inside TakeUserInput() you do all those cin << to set a global array or set of global variable. also, you cin << a, to terminate program at your will.
and inside PerformComparison(), you do what you have posted here in your question.

C++ Perfect Number With Nested Loops Issue

What I am trying to do is search for a perfect number.
A perfect number is a number that is the sum of all its divisors, such as 6 = 1+2+3.
Basically what I do here is ask for 2 numbers and find a perfect number between those two numbers. I have a function that tests for divisibility and 2 nested loops.
My issue is that I don't get any result. I've revised it & can't seem to find anything wrong. The compiler doesn't shoot out any errors.
What can be wrong?
#include <iostream>
using namespace std;
bool isAFactor(int, int);
int main()
{
int startval;
int endval;
int outer_loop;
int inner_loop;
int perfect_number = 0;
cout << "Enter Starting Number: ";
cin >> startval;
cout << "Enter Ending Number: ";
cin >> endval;
for(outer_loop = startval; outer_loop <= endval; outer_loop++)
{
for(inner_loop = 1; inner_loop <= outer_loop; inner_loop++)
{
if (isAFactor(outer_loop, inner_loop) == true)
{
inner_loop += perfect_number;
}
}
if (perfect_number == outer_loop)
{
cout << perfect_number << " is a perfect number." << endl;
}
else
{
cout << "There is no perfect number." << endl;
}
}
system("PAUSE");
return 0;
}
bool isAFactor(int outer, int inner)
{
if (outer % inner == 0)
{
return true;
}
else
{
return false;
}
inner_loop += perfect_number; should be perfect_number += inner_loop;.
There are other issues -- you need to reset perfect_number to zero in each outer loop, and you should presumably print the message "There is no perfect number." if none of the numbers in range is perfect, rather than printing it once for every number in range that is not perfect.
I'd advise that you rename perfect_number to sum_of_factors, outer_loop to candidate_perfect_number and inner_loop to candidate_factor, or similar.
after the if statement:
cout << perfect_number;
cout << outer_loop;
if (perfect_number == outer_loop)
{
cout << perfect_number << " is a perfect number." << endl;
}
and see what values they have
Updated:
What is the value of your endval? is 0?, and thats why the loop ends so early
Oh, so many issues.
The variable perfect_number never changes. Did your compiler flag
this?
The outer loop will be one more than the ending value when it exits;
did you know this?
You don't need to compare bool values to true or false.
You could simplify the isAFactor function to return (outer %
inner) == 0;.
You could replace the call to isAFactor with the expression
((outer % inner) == 0).