-2

I have the next code:

char shapetype;
std::cout << "which shape would you like to work with?" << std::endl;
std::cin >> shapetype;
switch (shapetype) {
    case 'c':
        std::cout << "enter color, name,  rad for circle" << std::endl;
        std::cin >> col >> nam >> rad;

If I writing for exemple 'cemfkem' in line 2, in shapetype I have c and the other part of the string is staying in the buffer so when i getting in the col, nam and rad the buffer get inside the col the other part of the string. how can I clean the buffer?

braX
  • 11,506
  • 5
  • 20
  • 33

1 Answers1

1

So you are using cin to fetch a single character and the buffer still has junk in it because your user entered nonsense.

The way to get rid of this is to use cin.ignore(). cin.ignore() takes 2 parameters an integer for the number of characters to ignore and a delimiter which will basically clearing the buffer if it reaches that character.

You'd probably want cin.ignore(<A REALLY BIG NUMBER>, '\n'); so that the buffer will clear out for a really long ways or until it reaches the return character whichever happens first.

Instead of using a hard coded big number, you could go and fetch the max size of the buffer like this:

//include this with your other #includes
#include <limits>


cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cwbusacker
  • 507
  • 2
  • 12