how to create message when loop completed - c++

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){

Related

Safe [Y/N]; [1/2/3/etc.] function

I tried to make a an introduction to a "game", and in its functions I made some Yes/No, 1/2/3, situations.
Im new to this however it wasn't that difficult, worked perfectly. The problem appeared when handling with invalid inputs. So this is what the code looks like by now:
#include "Introduction.h"
#include "GameConstants.h"
#include "PlayerCharacter.h"
#include <iostream>
#include <windows.h>
using namespace std;
Introduction::Introduction()
{
}
/////////Function N.1///////////
void Introduction::presentation()
{
char confirm;
string enteredName;
cout << constants.line() << "Welcome traveler! What is the name?" << endl;
getline(cin,enteredName);// Gets the WHOLE LINE as the name.
while (confirm != 'Y') //If the player doesn't confirm the name with 'Y' in will run again until it does.
{
cout << constants.xline() << "Your name is " << enteredName << " right? (Y/N)" << endl;
cin >> confirm; //The player's answer
cin.sync(); //Only takes the first character
confirm = toupper(confirm); //Turns player message into CAPS for easier detection in the "if" statements
if (confirm == 'N'){ //If not the correct name, gives another chance
cout << constants.xline() << "Please, tell me your name again..." << endl;
cin >> enteredName;
cin.sync();}
if ((confirm != 'Y')&&(confirm != 'N')){ //If an invalid input is entered, gives another chance. And insults you.
cout << constants.xline() << "Fool Go ahead, just enter your name again." << endl;
cin >> enteredName;
cin.sync();}
}
if (confirm == 'Y'){ //When the answer is yes ('Y') /* Uneeded line */
PC.setName(enteredName); //Saves the name
cout << constants.xline() << "Excellent! I have a few more questions for you " << PC.name() << "..." << endl;
}
}
//////////Function N.2///////////
void Introduction::difSelection(){
int selectedDif = 0; //Variable to store selected difficulty whitin this function.
Sleep(2500);
cout << constants.xline() << "What kind of adventure do you want to take part in?" << endl;
Sleep(2500); //Wait 2,5 s
cout << "\n1= Easy\n2= Normal\n3= Hard" << endl;
while(selectedDif != 1&&2&&3){ //Selected option must be 1/2/3 or will run again
cin >> selectedDif; //Sets the user selected difficulty
cin.sync(); //Gets only first character
if((selectedDif != 1||2||3)&&(!(selectedDif))){ //If the input isn't 1/2/3 AND is an invalid character, this will run. And it'll start again
cout << constants.xline() << "Criminal scum. Go again." << endl;
cin.clear();
cin.ignore();
}
if(selectedDif != 1&&2&&3){ //If selected option isn't 1/2/3, this will run and will loop again. However I know this conflicts with the previous statement since this will run anyways.
cout << constants.xline() << "Wrong input, please try again." << endl;
}
else if(selectedDif == 1){
constants.setDiff(1);
constants.setStatPoints(15);
} else if(selectedDif == 2){
constants.setDiff(2);
constants.setStatPoints(10);
} else if (selectedDif == 3){
constants.setDiff(3);
constants.setStatPoints(5);}
}
}
The first function works perfectly you can type "aaa" or "a a a" and will work. However I'd like to know if there's a simpler way to do it. (Understandable for a beginner, just started 3 days ago lol; if it includes some advanced or less known code prefer to stay like this by now).
Now, the second one, I really have no idea how to fix it. I need something that if the user's input was an invalid character type, throw certain message, and if it's an int type, but out of the range, another message. And of course, run again if it fails. Did a lot of search and couldn't find anything that meet this requirements.
To check if the user input is an int, you could use the good() function.
int val;
cin >> val;
if( cin.good() ) {
// user input was a valid int
} else {
// otherwise
}
As for the range check, the syntax is a bit different.
This returns true if the number is not equal to 1 nor 2 nor 3:
selectedDif != 1 && selectedDif != 2 && selectedDif != 3
Another shorter way would be to use:
selectedDif < 1 || selectedDif > 3
Another thing, in c++, there are two keywords break and continue which will allow to reduce the code in the loops.

C++ want to return to where left off

#include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;
int main()
{
int password;
system("cls");
cout <<"Login"<< endl;
cout <<"Enter password to continue"<< endl;
cin >> password;
cin.ignore().get();
if( password == 1111)
{
system("cls");
cout <<"Access Granted"<< endl;
system("PAUSE");
system("cls");
return main();
}
//Want to make if( password == 1111) return to main(), but start where it left off
//I want it to start at cout <<"Files:'<< endl;
cout <<"Files:"<< endl;
cout <<"\n E \n N \n G \n S \n"<< endl;
cout <<"Choose a file"<< endl;
string file;
cin >> file;
cin.ignore().get();
if(file == "E" || file == "e")
{
system("cls");
cout <<"E:"<< endl;
cout <<"Age:"<< endl;
cout <<"Grade:"<< endl;
cout <<"Eye color:"<< endl;
cout <<"Hair color:"<< endl;
system("Pause");
}
else if(file == "N" || file == "n")
{
system("cls");
cout <<"N:"<< endl;
cout <<"Age:"<< endl;
cout <<"Grade:"<< endl;
cout <<"Eye color:"<< endl;
cout <<"Hair color:"<< endl;
system("Pause");
}
else if(file == "G" || file == "g")
{
system("cls");
cout <<"G:"<< endl;
cout <<"Age:"<< endl;
cout <<"Eye color:"<< endl;
cout <<"Hair color:"<< endl;
system("Pause");
}
else if(file == "S" || file == "s")
{
system("cls");
cout <<"S:"<< endl;
cout <<"Age:"<< endl;
cout <<"Eye color:"<< endl;
cout <<"Hair color:"<< endl;
system("Pause");
}
else
{
system("cls");
cout<<"Access Denied!"<< endl;
system("PAUSE");
return 0;
}
return 0;
}
Having trouble figuring out how to continue where the main function left of. I have been teaching myself how to code so I don't know if that's even possible. Read the comment I left In the code to better understand what I am speaking of. Thx
If you remove this line:
return main();
then the computer will continue executing the instructions in the order they are written - in particular, the next one will be cout <<"Files:"<< endl;.
To control the flow of your program, you have multiple options.
If you're doing things multiple times, you have for and while loops. If you want to stop a loop and get out, use break. If you want to skip to the next iteration, use continue.
If you want to simply jump to a different place in the program, you can use goto but it's a code smell. It's generally better to avoid it as it tends to compromise readability.
If you want to do a task that can he interrupted, you can use a void function. If you want the function to stop what it's doing and continue main, use return.
However, in your particular example, it seems like you don't quite understand how an if statement works.
If the ifs condition is true, it executes whatever is in the curly braces ({ ... }). It continues execution right after the closing brace automatically. You don't need to return to main explicitly.
What you actually did there (by mistake) is write a recursive function (one that calls itself until a condition is met).
You seem to have significantly misunderstood program flow in a C++ program. return main() will make a fresh call into main, so the user will see the "login" prompt again. When that call to main has ended, because you used the keyword return, it will exit the previous call to main. Neither of these is what you want. It's also explicitly forbidden by the C++ standard to call main from another function.
I also note that after the long block of indented functionality, you have an else statement that looks like it is the else to if (password == 1111).
Indentation means nothing to the C++ compiler, it's purely for human readability.
I think what you are trying to achieve is something more like this:
if (password == 1111)
{
std::cout << "Access granted\n";
}
else
{
std::cout << "Access denied\n";
return 0;
}
std::cout << "Files:\n";
Here, if the user types 1111, then the first compound block of code is executed, and execution resumes after the end of the if/else block, i.e. the next instruction is to print Files.
If the user types something else, the else block is executed. It finishes with return 0 which exits the function and returns the value of 0 to the caller.
#include <iostream>
#include <string>
int main()
{
std::cout << "Login:\n";
std::string password;
std::getline(std::cin, password);
if (password == "1111")
std::cout << "That's correct.\n";
else {
std::cout << "Access denied.\n";
return 0;
}
std::cout << "Files:\n";
// your code here
}
Demo: http://ideone.com/DSYAG4

C++. If Statement won't exit

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.

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

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.