while loop, really don't understand - c++

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.

Related

Can't figure out why while loop is infinite

My code uses what I thought would be a simple while loop. It checks if the randCard already exists in the vector I have and, if it does, makes a new randCard.
I've added cout statements within the loop to try to find which processes it's running through and discovered it's only running through the while loop, none of the nested for loops. The problem is as follows:
bool isSame = true;
//Make sure they don't be the same cards
while (isSame){
cout << "While entered" << endl;
for(int i = 0; i < notToUse.size(); i++){
if(randCard == notToUse.at(i)){
randCard = rand() % 24;
}
cout << "First for ran" << endl;
}
for (int i = 0; i < notToUse.size(); i++){
if (randCard == notToUse.at(i)){
cout << "Recheck loop" << endl;
break;
}
else{
cout << "Else ran" << endl;
isSame = false;
}
}
}
randCard is from a class of type Cards. The vector notToUse consists of cards indices that have already been used. The end cout statements end up looking like:
While entered
While entered
While entered
While entered
While entered
It seems like the for loops aren't even accessed. How can I fix this?
For anyone who might stumble upon this, the answer was resolved in the comments. The vector was of size 0, so the for loops didn't even run.

Need help to stop program terminating without users consent

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.

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

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 do I keep track of letters guessed in a Hangman game in C++?

I have been trying to fix this program for the past two days and it is proving to be quite troublesome. It is an assignment for my intro to C++ course and has given me nothing but trouble. I have searched this board, posted on Cplusplus.com and spent hours on Google, looking for some assistance.
Here is my problem. I have been given a program and need to add a few features to it:
I have to save the users entries.
I have to display an error message if the user enters the same entry twice.
Seems simple? Not for a beginner such as myself. Here is the code, with what I have attempted to add to it in order to meet the problem's requirements.
int main()
{
//declare variables
string origWord = "";
string letter = "";
char dashReplaced = 'N';
char gameOver = 'N';
int numIncorrect = 0;
string displayWord = "-----";
string letterGuess[26];
//get original word
do //begin loop
{
cout << "Enter a 5-letter word in uppercase: ";
getline(cin, origWord);
} while (origWord.length() != 5);
//clear the screen
system("cls");
//start guessing
cout << "Guess this word: " <<
displayWord << endl;
while (gameOver == 'N')
{
cout << "Enter an uppercase letter: ";
cin >> letter;
//Entry Storage and Error Message. This is my problem.
for (int x = 0; x < 26; x++)
{
letterGuess[x] = letter;
for (int i = x; i < 26; i++)
{
if (i != x)
{
if (letterGuess[x] == letterGuess[i])
{
cout << "Letter already entered. Choose another letter."
<< endl;
}
}
}
}
//search for the letter in the original word
for (int x = 0; x < 5; x += 1)
{
//if the current character matches
//the letter, replace the corresponding
//dash in the displayWord variable and then
//set the dashReplaced variable to 'Y'
if (origWord.substr(x, 1) == letter)
{
displayWord.replace(x, 1, letter);
dashReplaced = 'Y';
} //end if
} //end for
//if a dash was replaced, check whether the
//displayWord variable contains any dashes
if (dashReplaced == 'Y')
{
//if the displayWord variable does not
//contain any dashes, the game is over
if (displayWord.find("-", 0) == -1)
{
gameOver = 'Y';
cout << endl << "Yes, the word is "
<< origWord << endl;
cout << "Great guessing!" << endl;
}
else //otherwise, continue guessing
{
cout << endl << "Guess this word: "
<< displayWord << endl;
dashReplaced = 'N';
} //end if
}
else //processed when dashReplaced contains 'N'
{
//add 1 to the number of incorrect guesses
numIncorrect += 1;
//if the number of incorrect guesses is 10,
//the game is over
if (numIncorrect == 10)
{
gameOver = 'Y';
cout << endl << "Sorry, the word is "
<< origWord << endl;
} //end if
} //end if
} //end while
system("pause");
return 0;
} //end of main function
My only edit to the program is directly under the header of Entry Storage and Error Message. I have tried a single for loop, but that simply displayed the error message for every letter entered. Not only that but it displayed it 26 times. Adding a Break command fixed that and it only displayed once. However, it still displayed on every entry.
A member of Cplusplus, pointed out that I was incorrectly testing the same variable against the array in the same location. That is why it displayed the error on every entry. Now with this loop, the error only displays when an entry is entered twice. However, the error message displays all 26 times once more. On top of that, it will only error if the letters are entered one after another.
For example, if I enter A then X then A again, no error is shown. If I enter, A then A again, the error is displayed 26 times. Something is clearly wrong with how the letter variable is being entered into the array on top of the whatever is causing the error message to display multiple times.
Any amount of assistance would be greatly appreciated.
Edit: My professor has gotten back to me and suggested using the following instead of what I have been tinkering with:
for (int x=0; x<5; x++)
if (origWord[x] == letterEntered)
origWord[x] = '-';
Is it just me, or does this miss the mark completely? I haven't tried converting it into my program as a simple copy and paste job produces compile errors. However, I don't see how that does anything with what I'm trying to do.
This set's all entries of your letterGuess array to the most recently guessed letter.
letterGuess[x] = letter;
This isn't what you want.
You need to think about the actual algorithm you need to implement:
The user enters a guess
Check to see if they've already guessed that letter
If they have, display an error message, return to 1.
If they have not, save that guess, continue with the game logic.
If you have already learned about standard containers, this can be trivially done with a std::set, or a std::vector that has been sorted.
You need to compare each element in the array to the guessed word. Best use a for loop for this. No more needs to be said if this is an assignment.
Also don't use system("cls") in your program, it is a massive security flaw and may lose you marks.