Nested While Loop

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
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
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?
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
This works, not sure I would do this but...

char junk;
Make a junk char variable.


1
2
cin.get(junk);
getline(cin, Answer);


We get junk that would clear the enter pressed by the user and then use getline.
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
Topic archived. No new replies allowed.