Usage of get() may not be the very best choice to recommend. For example, if one seeks input for an int, and the user enters "123abc" plus the newline, get() will only pop off the character 'a' and still leave the rest of the data in the stream.
Instead, use ignore(). This function takes two parameters: the marker character you seek (a newline), and the number of characters to ignore from the stream until you find the marker. For example:
Code:
cout << "Enter a number: ";
cin >> number;
cin.ignore(1024, '\n');
If you are concerned that some hacker may enter more than 1024 characters in an effort to subvert your application, then you could consider specifying the maximum sized value using something like:
Code:
#include <limits>
...
cin.ignore(numeric_limits<streamsize>::max(), '\n');
P.S. Of course, what's missing from the code above is the check to ensure that cin was able to obtain an int value in the first place.
Here's some code to ensure that input for a string, int, float, double, etc. is obtained successfully.
Code:
#include <string>
#include <iostream>
#include <limits>
template <typename T>
T getInput(const char* prompt)
{
using namespace std;
T input;
bool done = false;
while (!done) {
// prompt user and attempt to read input
cout << prompt;
cin >> input;
// check if valid input given; break from loop if so.
if (cin.peek() == '\n' && cin.good())
{
done = true;
}
else
{
// user gave bad input; let them know about it.
cout << "Invalid input! Try again...\n" << endl;
cin.clear();
}
do { cin.ignore(numeric_limits<streamsize>::max(), '\n'); } while (!cin);
}
return input;
}
int main(void)
{
char ch = getInput<char>("Enter a char: ");
std::string str1 = getInput<std::string>("Enter a string: ");
int num = getInput<int>("Enter a number: ");
std::string str2 = getInput<std::string>("Enter another string: ");
std::cout << "Your char is : " << ch << std::endl;
std::cout << "Your string is : " << str1 << std::endl;
std::cout << "Your number is : " << num << std::endl;
std::cout << "Your other string is: " << str2 << std::endl;
}
Bookmarks