Nov 8, 2013 at 8:27pm UTC
I was trying to figure out how to make a nested while loop that ends when a user inputs a specific string. I might be jumping the gun here and just need to run through each section of the tutorial but it seems close to working.
This is what I got.
It doesn't seem to be taking into account the "getline" and never asks for user input.
code updated, this works now.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
// custom countdown using while, User string to exit
#include <iostream>
#include <string>
using namespace std;
int main ()
{
int n, m = 1;
string Answer, Yes = "yes" ;
while (m == 1) {
cout << "Enter the starting number > " ;
cin >> n;
while (n>0) {
cout << n << ", " ;
--n;
}
cout << "FIRE!\n" ;
cout << "Run Again?\n" ;
cin >> Answer;
cout << "You Entered " << Answer << "\n" ;
if (Answer != Yes) {
m = 0;
}
}
return 0;
}
Last edited on Nov 8, 2013 at 8:55pm UTC
Nov 8, 2013 at 8:45pm UTC
getline(cin, Answer);
is picking up the the return key pressed after your user enters a number and presses enter here cin >> n;
Because you are looking for a one word answer you could change getline(cin, Answer);
to cin >> Answer;
.
Last edited on Nov 8, 2013 at 8:45pm UTC
Nov 8, 2013 at 8:52pm UTC
Thanks, that solved my input problem.
I fixed the code up top so it works properly.
Out of curiosity, would it be a simple fix for the input problem if I wanted to use getline?
Nov 8, 2013 at 8:56pm UTC
There is a few things:
while (m = 1)
should be
while (m == 1)
You're not comparing the value of m to 1, but instead assigning 1 to m.
Also I'm not sure why you're associating "Yes" with m = 0
since that would make the condition false and not loop again.
Last edited on Nov 8, 2013 at 8:58pm UTC
Nov 8, 2013 at 9:00pm UTC
I noticed that behavior after I posted, I will have to remember that values can still be assigned to variables even within the while ().
I was trying to use an integer to end the while loop because I had errors trying to compare two strings inside the while loop.
I think I'll try to figure out how to do that next, if it's possible. I just don't know to be honest.
Can you do
1 2 3 4 5
while (String1 == String2) {
code that does stuff
}
Last edited on Nov 8, 2013 at 9:10pm UTC