1

My program takes user data as a tuple and stores it into a vector. There is no limit to how many tuples can be added and vector size changes with the adding of tuples. The program asks the user if they want to add another tuple. If no, the loop exits.

My problem is, when the program was supposed to wait for 'yes' or 'no' input, it skipped the cin and exited the loop.

I have tried searching for solutions, tried clearing the buffer but I am back to square one.

#include <iostream>
#include <string>
#include <tuple>
#include <vector>
using namespace std;

void print(vector<tuple<int, string, string, bool>> const & data)
{
    if (data.size() != 0)
    {
        for (auto row : data)
        {
            cout << get<0>(row) << ", " << get<1>(row) << ", " << get<2>(row)
                 << ", " << get<3>(row) << endl;
        }
    }
    else
    {
        cout << "\nNO ENTRIES CURRENTLY!";
    }
}
int main()
{
    int id;
    char go;
    string name, filePath;
    bool flag = false;
    typedef tuple<int, string, string, bool> pData;
    vector<pData> pList;

    do
    {
        cout << "Enter a Pattern Call:" << endl;
        cin >> id >> name >> filePath >> flag;

        pList.push_back(make_tuple(id, name, filePath, flag));

        cout << "Do You wish to add another: ";
        cin.ignore();
        cin >> go; //The control skips here and exits the loop.
    } while (go == 'y' || go == 'Y');

    print(pList);

    return 0;
}
user4581301
  • 33,082
  • 7
  • 33
  • 54

2 Answers2

1

I have a hack which seems to work on my Linux Machine.

  1. Add cin.clear() before cin.ignore()

  2. Replace cin.ignore() with cin.ignore(1)

Part of your code should look as below:

    cout << "Do You wish to add another: ";
    cin.clear();
    cin.ignore(1);
    cin >> go; //The control skips here and exits the loop.
hmatar
  • 2,437
  • 2
  • 17
  • 27
0

Look here: How do I flush the cin buffer? Using cin is not that easy or safe if user input is not exactly what we want.

Community
  • 1
  • 1
Ali Asadpoor
  • 327
  • 1
  • 13