Really weird problem

Ok so i have a program that has you enter numbers and you get a score, i am testing it along the way and when you enter 4 lines of numbers it gives me the error message, why is that?

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
#include <iostream>
#include <windows.h>
#include <string>
#include <time.h>

using namespace std;

int randNumbers();

int main()
{
    bool endLoop = false;
    int enter;
    int score;
    string s;

    cout << "in this game you will have to enter numbers to continue" << endl;
    cout << "Lets begin! press enter\n" << endl;
    cin.get();

        while(endLoop != true)
        {
            if(cin >> s)
            {
                cout << "error" << endl;
            }
            if(cin >> enter)
            {
                cin >> enter;
                cout << randNumbers() << endl;
            }
            else
            {
                cin.clear();
            }
        }
}

int randNumbers()
{
    srand(time(0x0));

    for(int i = 0; i < 50; i++)
    {
        int r = rand() % 60000000000;
    }
}
bump
Every time you use the >> operator the program is waiting for you to hit enter. The >> operator also stops reading at white space.

Your program starts waiting at line 23, reads the string and gives an error message (since you can pretty much count on that statement evaluating to true). The program waits at line 27 for you to enter a number. If you do, the program waits at line 29 for you to enter another number.

So you need to only have one >> operation, and change the order a little:
1
2
3
4
5
6
7
8
9
10
11
while (!endLoop)
{
  if (cin >> enter)
    cout << randNumbers() << endl;
  else
  {
    cin.clear();
    cin.ignore(80 ,'\n');
    cout << "Error\n";
  }
}


Also, put your srand() at the beginning of main. The seed should only happen once.
Last edited on
Topic archived. No new replies allowed.