C++ Input Validation

βœ… C++ Input Validation

Input validation ensures that the data entered by a user is correct, safe, and usable before your program processes it.
Good validation prevents crashes, wrong results, and security issues.


πŸ”Ή 1. Why Input Validation Is Important

  • Prevents invalid data (letters instead of numbers)

  • Avoids infinite loops and crashes

  • Improves user experience

  • Essential for real-world programs


πŸ”Ή 2. Basic Numeric Input Validation (cin)

When invalid input is entered, cin goes into a fail state.

int x;
cin >> x;

if (cin.fail()) {
cout << "Invalid input!";
}


πŸ”Ή 3. Clearing Invalid Input (Best Practice)

#include <iostream>
#include <limits>
using namespace std;

int main() {
int x;

while (true) {
cout << "Enter an integer: ";
cin >> x;

if (!cin.fail()) {
break; // valid input
}

cout << "Invalid input. Try again.\n";
cin.clear(); // clear error state
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // discard bad input
}

cout << "You entered: " << x;
}


πŸ”Ή 4. Validate Input Within a Range

int age;

do {
cout << "Enter age (1–100): ";
cin >> age;
} while (age < 1 || age > 100);


πŸ”Ή 5. String Input Validation

Check Empty String

string name;
getline(cin, name);

if (name.empty()) {
cout << "Name cannot be empty";
}


Check Alphabetic Characters Only

#include <cctype>

bool isValid = true;
for (char c : name) {
if (!isalpha(c) && c != ' ') {
isValid = false;
break;
}
}


πŸ”Ή 6. Validate Menu Choice

int choice;

while (true) {
cout << "1. Add\n2. Edit\n3. Exit\nEnter choice: ";
cin >> choice;

if (cin.fail() || choice < 1 || choice > 3) {
cout << "Invalid choice!\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
} else {
break;
}
}


πŸ”Ή 7. Validate Integer Using getline + stoi (Robust)

string input;
int value;

while (true) {
cout << "Enter a number: ";
getline(cin, input);

try {
value = stoi(input);
break;
} catch (...) {
cout << "Invalid number. Try again.\n";
}
}

βœ” Handles mixed input safely
βœ” Very reliable


πŸ”Ή 8. Validate Floating-Point Input

double price;

while (!(cin >> price)) {
cout << "Invalid price. Try again: ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}


πŸ”Ή 9. Validate Yes/No Input

char choice;

while (true) {
cout << "Continue? (y/n): ";
cin >> choice;

choice = tolower(choice);
if (choice == 'y' || choice == 'n')
break;

cout << "Invalid choice!\n";
}


πŸ”Ή 10. Common Mistakes ❌

int x;
cin >> x; // user enters "abc"
// program continues incorrectly

βœ” Always check cin.fail().


πŸ”Ή 11. Best Practices for Input Validation

  • Always validate user input

  • Clear input buffer after invalid input

  • Use loops to re-prompt users

  • Prefer getline() + conversion for complex input

  • Validate ranges and formats


πŸ“Œ Summary

  • Input validation prevents invalid data

  • Use cin.fail() to detect errors

  • Clear input using cin.clear() and cin.ignore()

  • Validate ranges, strings, and menu choices

  • Essential for real-world, safe C++ programs

You may also like...