Why Does This Happen?

I was just trying some new things and I came across this. I was thinking "Could I use a string instead of an integer so instead of pressing "1" for yes, you press y." After I did this the program kept crashing once it got to this line of code, anyone know why? Is there a way I could do this since this is obviously not the right way. Also is there a way I can make it where you type out the word "yes" or any word and make it do something?

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
50
51
52
53
54
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>

using namespace std;

int main()
{
    int p;
    int c;
    int a;
    string y;

    do{

    do{

    cout << "Enter a number 1-10\n";
    cin >> p;

    }while ( p > 10);



    srand(time(0));
    c = rand()%10 + 1;

    cout << "The computer chose " << c << endl;
    cin.get();

    if (c > p){
    cout << "You lose!\n";
    }

    if (c < p){
    cout << "You win!\n";
    }

    if (c == p){
    cout << "Tie!";
    }

    cout << "Do you want to play again?\n\n";
    cin >> a;

    string y = y;


    }while (y == y);

    cout << "thanks for playing";

}
There's quite a few things wrong:

1) Row 45 still reads an int ('a', instead of string 'y').
2) Row 47 re-declares string y. It's already declared at row 13.
3) Aside from re-declare string y, it also tries to initialize variable y using its own value (string y = y). This makes no sense. You want to use 'y = "y"' instead: assign the string literal "y" to variable y.
4) Same problem at row 50: you're comparing the value of variable y to the value of variable y, which is by definition always true. You want to compare it to the string literal "y", not y.

Thus, change row 47 to "cin >> y", remove row 47 and chance row 50 to '}while (y == "y");'.

And, to avoid confusion in following questions, try giving string y a different name. It's very confusing that y has to be "y".
Last edited on
Oh I see! That works perfectly, thanks for the quick reply and awesome answer Gaminic!
Topic archived. No new replies allowed.