converting int - string

Hello I have created the following program to test out the rand() function and converting values (int - string).

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
#include <iostream>
#include <stdlib.h>
#include <sstream>
#include <ctime>

using namespace std;


int main (void) {

srand(time(0));

int x, tryNumber;
bool correct = false;
string guess, xstring;
ostringstream convert;


cout << "Guess the number 1 - 10!\n";

while (correct != true)
{
              
        x = rand() %10 +1;
        
        getline(cin,guess);
        convert << x;
        xstring = convert.str();
        
        if (guess == xstring)
        
        {
                  correct = true;
        }
        
        else
        
        {
             cout << "That was wrong! The correct number is " << x << "\nTry again !\n";
             tryNumber++;
             correct = false;
        }     
}
      
cout << "Well done! You guessed the number in " << tryNumber <<" try(s)!";


cin.get();

return 0;

}


The problem is that if I enter a number that was correct, for example I am entering '1' in all the time, this would happen:


1
That was wrong! The correct number is 1
Try again !


The only time this has not happened would be when I have guessed the correct number first try, however the try number was incredibly large.

I think the conversion of the int to a string is what is causing the first problem, however I do not know how to fix it, I don't know how to fix the second problem either.

Would someone tell me how I could fix this?

Thanks in advance.
Content of xstring after 1 guess: "3"
after 2 guesses: "31"
after 3 guesses: "317".
Do you understand now?

Problem with try number is that you never assigned anything to it, so starting value will be garbage: essentially random.
Last edited on
Ah okay thank you, can't believe I didn't think of that all this time ...

edit :

By the way would that mean I would have to clear xstring from any values each time the user guessed ?
Last edited on
Not the xstring: you should clear convert stream. xstring will be replaced each time on line 28. convert will stay.
Thanks a lot!

I managed to clear convert by
1
2
3
4
getline(cin,guess);
        convert.str("");
        convert << x;
        xstring = convert.str();


Why not simply input the number directly into an integer?

1
2
int guess;
std::cin >> guess;


Last edited on
Then I wouldn't be testing the method for converting an integer into a string.
The point of the program was to test out methods I know I will find useful in the future.
Last edited on
In C++11, you can use std::to_string():
http://en.cppreference.com/w/cpp/string/basic_string/to_string
Topic archived. No new replies allowed.