Hello, Im trying to write this code where it asks to enter a guests name, after entering it, it asks you if you'd like to add another, if you put yes it needs to repeat, if no than its supposed to present the cout statement where the data has been saved, my problem is the option for no runs infinitely and I need it to only run once
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
string name;
char choice;
cout << "please enter the name" << endl;
cin >> name;
cout << "enter another?" << endl;
cin >> choice;
while (choice == 'y' || choice == 'n')
{
if (choice == 'y')
{
cout << "okay, please enter the next name" << endl;
cin >> name;
cout << "Enter another?" << endl;
cin >> choice;
}
else if (choice == 'n')
{
cout << "data has been saved!" << endl;
}
}
while (choice == 'y' || choice == 'n')
You need to let them get out of the loop somehow. If they enter 'n', it just outputs the message, checks the while condition again, choice is still n so it ouputs the message, checks the while condition again, etc etc.
Think about it logically: the loop is set to run if the choice is 'yes' or 'no,' so it's always going to run regardless of the input. Here's one way of setting up the loop.
string name;
char choice;
cout << "Enter a name: ";
cin >> name;
cout << "Enter another? ";
while (cin >> choice) // the way this loop works is that it continues if the input
{ // is valid. since 'choice' is a char, any non-char will skip the loop
if (choice == 'y')
{
cout << "Okay please enter the next name: ";
cin >> name;
cout << "Enter another? ";
// reiterates the loop so if 'y', it branches here again and so on.
}
elseif (choice == 'n')
{
cout << "Data has been saved." << endl;
break; // breaks the loop like it would break a case in a switch statement
}
}