SkippyNBS
SkippyNBS

Reputation: 777

C++ Function Skipping Code

I have written the following code, which compiles fine. However, when I run it, it skips the getline(cin, p[x]); the second time the function is called. Can anyone tell me why?

Here's the code:

#include "stdio.h"
#include "simpio.h"
#include "strlib.h"
#include "iostream.h" 
#include "random.h"

int Hp[2], Atk[2], Ddg[2];
std::string p[2];

void player(int x)
{
    cout << "Player name: ";
    getline(cin, p[x]);
    cout << "\tHp: ";
    cin >> Hp[x];
    cout << "\tAtk: ";
    cin >> Atk[x];
    cout << "\tDdg: ";
    cin >> Ddg[x];
}

main()
{
    string go;

    player(0);
    player(1);

    cout << "Go? (Yes/No): ";
    cin >> go;
    cin.get();
}

Upvotes: 0

Views: 518

Answers (3)

aghoribaba
aghoribaba

Reputation: 131

I think its because there is still a \n left in the input stream. Try a cin.ignore() before using getline. I hope it works.

Upvotes: 3

Saraph
Saraph

Reputation: 1002

Your cin stream isn't flushed from first use and getline assumes input has been done already. You can flush it using:

cin.clear(); //clear any possible bits
cin.ignore(); //throw away whatever is there left in the stream

Upvotes: 2

David G
David G

Reputation: 96835

The code appears to be "skipping" the second call to std::getline() because the previous call to player() performed an extraction through std::cin that left a newline in the stream. std::getline() only reads characters until the next newline - so what appears to be skipping is just std::getline() failing to input characters because of the residual newline.

The solution is to clear the newline using std::ws:

std::getline(std::cin >> std::ws, p[x]);

Upvotes: 2

Related Questions