C++. If Statement won't exit - c++

I have a function with a while loop and some if statements in it, everything runs as expected, however, when the If statement that should return the vector select_control value runs, it doesn't terminate the function after returning a value.
vector<int> select() {
vector<int> select_control;
int select;
cin >> select;
while (select < 10) {
//SOME CODE THAT PUSHES VALUES INTO THE VECTOR select_control
}
if (select == 99){
cout << "TERMINATING";
Sleep(3000);
exit(0);
}
else if (select == 100) {
cout << "input complete";
return select_control;
}
else {
cout << "not a valid value";
}
}

Rather than exit(0); in your conditional statement, put a break;.

Use the break; syntax. This exists out of the if stement, you don't have to include anything.

Well for starters your loop never ends because select never gets updated for the loop to eventually become false, you can add a break; after it does return select_control or you can just do exit(0); if there's absolutely nothing else the program is gonna do. You should also add break; or exit(0) after cout << "not a valid value"; because select isn't being updated for the while loop to become false and exit.

Related

Multiple if-else in C++

I am getting confused with a simple program of multiple if-else in c++. The code
is given below.
include<iostream.h>
void main()
{
int i;
cout<<"Enter the number:";
if(i==1)
{
cout<<"Sunday";
}
if(i==2)
{
cout<<"Monday";
}
else
{
cout<<" invalid input";
}
}
When I try to run this code ,the output shows this.
Enter the number:1
Sunday invalid key
So my question is why the output executing the Else part though the output is True..? Please help me . Thank You
This is because you don't have "multiple if-else", really. You have a single if (without else), then another if. The two are independent. You probably wanted:
if(i==1)
{
cout<<"Sunday";
}
else if(i==2)
{
cout<<"Monday";
}
else
{
cout<<" invalid input";
}
This makes sure the final else block only runs if none of the preceding conditions are met.
First you check whether i equals one. If it is the case, "Sunday" is printed. The if statement is finished at that point. Afterwards you check (in a separate if statetement) whether i equals two, you print "Monday" if it is the case, or "invalid input" if it is not the case. To obtain the result you want, write
else if (i == 2)
to have the second if/else statement only executed if i is not 1.
Alternatively, you might want to use a switch statement.
switch(i)
{
case 1:
cout << "Sunday";
break;
case 2:
cout << "Monday";
break;
default:
cout << "invalid input";
break;
}
But don't forget the breaks if using switch!
You have to put else if, if you wanna have the right processing:
if(i==1)
cout<<"Sunday";
else if(i==2)
cout<<"Monday";
else
cout<<" invalid input";
With else if, the second and the third condition are not processed, because the first one is alredy valid. In your code, it is first processed the code under the first condition, than because the input is not equal to 2, the code under the else is processed.
There are several bugs in this code. I explained and fixed it here-
#include<iostream.h>
void main()
{
int i;
cout<<"Enter the number:";
cin >> i; //take the input number from the user
if(i==1)
{
cout<<"Sunday";
}
/* the i==1 and i==2 block will run separately unless you connect them with an else */
else if(i==2)
{
cout<<"Monday";
}
else
{
cout<<" invalid input";
}
}
This is cause you have used two branching statement for same input
1. The first if() statement check if your value is equal 1 or not
if(i == 1)
std::cout << "Sunday"; // here you have print "Sunday for 1
2. Then again you check your value with another if-else statement
if(i == 2)
std::cout << "Mondey";
else
std::cout << "invalid input"; // here you have print "invalid input"
//since i is not equal to 1
You have two different conditions. One is:
if(i==1) {
cout<<"Sunday";
} // this statement ends here.
The other:
if(i==2) {
cout<<"Monday";
} else {
cout<<" invalid input";
}
The second is always going to result " invalid input" when i is not 2.

Check function going into infinite loop and segmentation fault

void InputStatisticalData()
{
//variables declaration
cout << "\n[Here to take in data]" << endl;
//cin data
while (exit == false)
{
cout << "Entered Loop" << endl;//for troubleshooting purpose
cout << "CountCheck: " << countcheck << endl;//for troubleshooting purpose
if (!Vector.empty())
{
cout << "Entered Vector check IF" << endl;//for troubleshooting purpose
if (condition)//checks if data has any duplicates
{
cout << "\nData already exist, please enter a new set of data." << endl;
break;
}
else
{
cout << "Entered countcheck++" << endl;//for troubleshooting purpose
countcheck++;
}
}
else
{
//stores data
exit = true;
}
}
}
Hi guys, above is my function to take in some data and store them into an object before storing into a vector. Everything works fine, therefore i decided to do some validation checking for the function. 1 of it is to check if the data keyed in, is it already been keyed in before.
I can store the data once and that's it, once i attempt to store it again, it will go into an infinite loop and give me a segmentation fault. I have been trying to solve it for a week but to no avail.
Another infinite loop is the cin.fail. It goes into an infinite loop as well if a wrong input is detected.
Thanks for taking your time to take a look.
Lol, why keep down-voting my questions, there's a question and a solution, it's suppose to help others, so stop down-voting and upvote it
You are dealing with an infinite loop because the error flags are not reset at the end of your iterations.
You should do a cin.clear() to reset the failbit before attempting any other operations:
if(cin.fail())
{
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //skip bad input
...
}
On your second loop, you check if the vector of data is empty or not. If it is not empty (a second entry) and your data is new, it will fall indefinitely in the else statement that increases countcheck.
Two things may happen: an infinite loop or a segmentation fault (out of bounds exception).
You should check for an upperbound limit, e.g.:
if(countcheck > Vector.size())
{
//This data is new
PTD.setLD(LD);
Vector.push_back (PTD);
cout << "\nRecord stored successfully, returning back to main menu." << endl;
exit = true;
}
else if(Vector[countcheck].getX() == MainX &&
...
}
You could also use a for statement instead:
for(countcheck = 0; countcheck < Vector.size(); countcheck ++)
{
if(Vector[countcheck].getX() == MainX && ...)
{
...
exit = true;
break;
}
}
//New element
if(countercheck == Vector.size())
{
PTD.setLD(LD);
Vector.push_back (PTD);
cout << "\nRecord stored successfully, returning back to main menu." << endl;
exit = true;
}

how to create message when loop completed

I have a code working on basic c++. I just want when this loop become completed and one if statement become true, a message generate automatically. In this regard i have used while statement but while statement is also work i don't want to display the message. Means when if statement (congratulation....) become true, the message (You don't have more...) displays.
for(i=1; i<=attempt; i++){
cout<< "whatever" ;
cin >> userNumber;
if (userNumber < secretNumber){
cout << "Oooppssss... Your entered number is too low..." <<endl;
}
else if (userNumber > secretNumber){
cout << "Oooppssss... Your entered number is too high..."<<endl;
}
else if(userNumber==secretNumber){
cout << "Congratulation you have won..."<<endl;
break;
}
else{
cout << "Invalid Input."<<endl;
}
}
while(attempt=i){
cout<< "You don't have more turn...Computer Won."<<endl<<endl;
break;
}
Reason is you are not using == and hence condition always turns true. Also instead of while loop you need if
while(attempt=i){
Use
if((attempt + 1) == i){

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++ if...then statement

So I'm trying to make a simple application that quizzes the user. It asks a question and the user answers 1, 2, 3, or 4. The app then takes that answer and if it is correct adds +1 to the total_score which will be displayed at the end. Everything looks sound to me, but when I run it and I get to the if (q1_valid == false) part it skips the cout and runs the goto no matter if q1_valid is true or false.
#include <iostream>
using namespace std;
int main()
{
int q1_answer;
int total_score;
bool q1_correct;
bool q1_valid;
Question_1:
cout << "Question 1 (#3 is correct)" << endl;
cout << "1.) Answer 1" <<endl;
cout << "2.) Answer 2" <<endl;
cout << "3.) Answer 3" <<endl;
cout << "4.) Answer 4" <<endl;
cin >> q1_answer;
if (q1_answer == 1)
q1_correct = false;
q1_valid = true;
if (q1_answer == 2)
q1_correct = false;
q1_valid = true;
if (q1_answer == 3)
q1_correct = true;
q1_valid = true;
if (q1_answer == 4)
q1_correct = false;
q1_valid = true;
if (q1_valid == false)
cout << "Invalid answer." <<endl;
goto Question_1;
if (q1_correct == true)
cout << "Correct!" <<endl;
(total_score + 1);
goto Question_2;
if (q1_correct == false)
cout << "Incorrect." <<endl;
goto Question_2;
if (q1_valid == false)
goto Question_1;
Question_2:
cout<< "Q2" <<endl;
cin.ignore();
cin.ignore();
}
I have a few tips here:
If... then is a conditional, not a loop. Sorry, that's just me being slightly picky. ;)
Never, ever, ever, ever use goto. ADVANCED USAGE: only use goto when there's a damned good reason to.
When testing boolean values, you don't need "== true" or "== false".
It looks like you haven't learned how to use the else statement yet. That's going to make your program a lot easier to read, debug, and understand.
Brackets are also necessary, as noted above.
You need to use brackets:
if (q1_valid == false) {
cout << "Invalid answer." <<endl;
goto Question_1;
}
If you don't use the brackets, the if only executes the first statement directly following it, if the if condition evaluates to true.
You don't have braces around the statements after the if, so only the first statement is conditional. In this case, that means that "q1_valid=true;" runs no matter what the answer is.
if (q1_answer == 4) {
q1_correct = false;
q1_valid = true;
}
You need an editor which shows you this by indentions.
emacs will, for example
Brackets for the if statement are required.
Have you considered using the switch statement:
switch (q1_answer){
case 1:
q1_correct = false;
q1_valid = true;
break;
case 2:
q1_correct = false;
q1_valid = true;
break;
case n:
//...
break;
}
Don not forget to use brackets.