While Loops for my Text RPG

I am trying to make a Text RPG game, But I can't seem to get do while or while to work. Here is my code.

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#include <string>
#include <cmath>
#include <time.h>
using namespace std;

void first();

void first()
{
	
	int x;
	
	
	
	
	
		
	cout << "You awake in a strange forest, you are dizzy and disoriented, and you see a large" << " \n" << "castle far in the distance. You feel a sharp pain in your back. You black out. \n" << endl;
	cout << "1) Wake-up" << endl;
	cin >> x;
	
	if (x==1)
	cout << "You awake in a prison cell, in what looks to be the large castle you observed" << " \n"  << "earlier.  \n";
	
	else
		first();
		
	

		
	

	
}



int main()
{
	first();

	


	system("pause");
	return 0;

}


When I run this, everything works fine, up until I enter something other than 1 for the variable X. It just makes the loop go on forever. What do I do to get this to work?
Last edited on
Firstly, This has neither a do-while or a while loop.
Secondly, You're using recursion here. If you recurse too much you can smash your stack.
Thirdly, Your problem is that you're using cin >> x; without using a cin.ignore() to ignore any newline characters stored in the buffer.
I know it doesn't. I wanted to know how to just go back to the variable 'first' without any input after you enter something other than 1.
Also, adding cin.ignore just broke the program even more. Now entering 1 isn't even working right.
1
2
cin >> x;
cin.ignore('\n');
that just makes a new line I can't do anything on. Like last time. But that isn't the problem. The problem I need fixed is exactly what I stated before. "I wanted to know how to just go back to the variable 'first' without any input after you enter something other than 1."
I hate working with cin. Anyways, here is some code I tested that works using recursion.

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
void first() {
 cout << "Something something something darkside" << endl;
 cout << "1) Family Guy Reference" << endl;
 
 string temp;
 getline(cin, temp);

 stringstream ss;
 ss << temp;
 
 int x = 0;
 ss >> x;

 if (x == 1)
     cout << "Something!" << endl;
 else
     first();

}

int main() 
{
    first();

    system("pause");	
	return 0;
}
Topic archived. No new replies allowed.