Skip to content

Commit

Permalink
fix cin buffer not flushing
Browse files Browse the repository at this point in the history
  • Loading branch information
navidmafi committed Jun 14, 2022
1 parent cd63c02 commit 3082e51
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 9 deletions.
27 changes: 20 additions & 7 deletions DisplayController.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,40 @@ All rights reserved.
// Migrated to iostream because i really did not want to manually handle char buffers.
#include <iostream>
#include <iomanip>
#include <limits>
#include <string>
#include "DisplayController.h"

using std::cin;
using std::cout;
using std::endl;
using std::ws;

// I will try to use the "Single Responsibility Principle" here as much as i can.
int DisplayController::readInput(int min, int max)
{
int userInput = 0;
scanf("%d", &userInput);
while (userInput < min || userInput > max)
while (true)
{
cout << "Invalid input, please try again: ";
cin >> userInput;
if (cin.fail())
{
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
logger("error", "Invalid input, please try again");
}
else
{
if (userInput < min || userInput > max)
{
logger("error", "Invalid input, please try again");
}
else
{
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return userInput;
}
}
}
cin.ignore();

return userInput;
}
template <typename T>
T DisplayController::readOptionalInput(T defaultValue)
Expand Down
3 changes: 1 addition & 2 deletions main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@ This source code is provided only for reference purposes. This is not a public d
All rights reserved.
*/

#include <stdio.h>
#include <sqlite3.h>
#include <iostream>
#include <sqlite3.h>
#include "ContactController.h"
#include "DisplayController.h"

Expand Down

0 comments on commit 3082e51

Please sign in to comment.