Repeat specific cout until it is true.

The variable/data type is a string named UN.
I would like to repeat the same cout statement while the cin is not equal to my liking.

Example:
cout<<"Ketchup:";
cin>> UN;
if(UN=="potatoes");cout<<"fries";

but if potatoes is not entered, then I would like to cout<<" ketchup"; forever until it is finally entered correctly.

I would like to output "ketchup" as long as the input is not equal to my desired cin>> which is potatoes. And then when cin>> is potatoes I would like to move on to a new cout statement such as cout<<"Mustard:";

I have tried if and else conditions. I have tried the while loop and it kept repeating without stopping.

Please just give me hints, as I want to figure this out with minimal help.

Thank you in advance.

KP
if's and else's probably won't help you here, though that while loop could have worked.

(Keep trying with a while loop at the moment, and come back if you need some more help.)
Heres what I have:

#include <iostream>
#include<string>
using namespace std;
string UN;

int main()
{
cout<< "Ketchup:";
cin>> UN;
while (UN!="potatoes");{cout<<"Ketchup:";}
}

When I run this and dont enter potatoes, it returns a blinking cursor.

When I run this and enter potatoes it returns ketchup, even though I told it not to.

Do I need to add a new cin>> after the last cout<<?
Should I add another while loop while(UN=="potatoes"; and then have a cout<< for that??
I don't think you're quite getting the concept of while loops.

This is how they work:

1
2
3
4
while(something)
{
    While something is true, do this.
}


Putting a while after your code won't work... Keep trying though.

Also, please use [ code] [ /code] tags
Last edited on
I would use a do while loop like this:
1
2
3
4
5
6
7
8
int main()
{
	do 
	{
		cout << ketchup;
		cin >> UN;
	} while(UN != "potatoes");           
}


And the reason u get Ketchup repeated forever in
1
2
3
4
5
6
int main()
{
cout<< "Ketchup:";
cin>> UN;
while (UN!="potatoes");{cout<<"Ketchup:";}
}

is because you say "while UN does not equal potatoes, print ketchup."
So, if you don't give the user a chance for input to change UN's status or break
from it, then you get the infinite loop.
Last edited on
Thank you Ben Duncan and WR417H!!!

The devil is in the details! My {} were in the wrong places and that is indeed why I received the infinite loop. I was including while within the {}. The infinite loop was occurring in combo with an if condition also.

Always learning!

KP


Topic archived. No new replies allowed.