Newbie needing help!

Hi!

I tried writing this program and when I built and run the program it works fine once, but if I press 1 at the end of the program to start again the program jumps over the first line asking for the first player's name automatically.

I do not know how to get around this error and I it is very difficult to google it because it is very specific.

Thank you for your help!

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
55
56
57
58
59
60
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;

int main(){

int counter;

string a,b,x,y,z;

    cout << "Please insert your name: \n";
    getline(cin,a);

    cout << "Please insert your name: \n";
    getline(cin,b);

do{
    counter==0;

    cout << a << " pick a question \n";
    cout << "Insert your question: \n";
    getline(cin,x);

    cout <<"And the answer is... \n";
    getline(cin,y);

    system ("cls");

    cout << a << " Asks : " << x << endl;
    cout << b << " Your answer is ...  ";
    getline(cin,z);

if(y==z){
    cout << b << " Answered correctly and won this round \n \n";
}
if(y!=z){
    cout << b << " did not answer correctly  " << a << " won this round !!! \n \n";
}
    cout << a << " asked " << x << endl;
    cout << " The correct answer was: " << y << endl;
    cout << " and " << b << " answered " << z << endl;
    cout << "\n \n Would you like to continue? \n" << endl;
    cout << "1.Yes \n2.No" << endl;
    cin >> counter;
    system ("cls");

} while (counter<2);

    Sleep(0700);
    cout << "LOADING ";
    cout << "." ;
    Sleep(0700);
    cout << ".";
    Sleep(0700);
    cout << ". \n";
    Sleep(0700);

    return 0;
}


I think that your problem is same as in this:
1
2
3
4
5
6
using std::cin;
std::string word;
int number;

cin >> number;
std::getline( cin, word );

Line 5 does formatted input. It will skip leading whitespace, read integer, and leave the non-digit following the number into the stream.

Typical user presses 'Enter' after the digit. A newline character.

Line 6 does unformatted input. It copies everything into word, except next newline, which is then removed from the stream.

Oh no! The line 5 left bare newline to the stream, so the "everything" that gets copied contains nothing.

As test, when your program asks for 1 or 2, do write:
1fubar

It will still "skip" the first question, but actually that question will get "fubar" as input.


So, what to do? You have to remove the (probable) newline character from the stream after the cin>>counter

See the member ostream's function ignore
Last edited on
Also read this in-depth explanation (although no one I posted it to actually read it. THey just seems to grab first line of code posted in solution and stop reading further)
http://stackoverflow.com/a/21567292
Topic archived. No new replies allowed.