vendredi 6 décembre 2019

How do I clear the cin buffer? [duplicate]

This question already has an answer here:

So I've been scratching my head at this issue for a while and it has me stumped.

I take an integer input just before I get into the inner for loop. Everything works fine until then but then my loop runs only n-1 times when it should run for n times and take n string inputs.

int t; cin>>t;
    for(int i=0;i<t;i++) {
        int n; cin>>n;
        vector<string> trainSet;
        for(int j=0;j<n;j++) {
            string str;
            getline(cin, str);
            //trainSet.push_back(str);
            if (j==0) trainSet.push_back(str);
            else add_if_valid(trainSet, str);

I tried to display the contents of 'trainSet' and apparently the first one is a blank character. Why is this happening? Doesn't cin get cleared when I enter a value for int n?

Appreciate any help I can get.

Aucun commentaire:

Enregistrer un commentaire