C++ Input Validation
Ensuring user input is safe and correct
🛡️ What is Input Validation?
Input validation checks if user input meets expected criteria before processing. It prevents errors, crashes, and security issues by ensuring data is safe and correct.
int age;
cout << "Enter age: ";
cin >> age;
if (age < 0 || age > 150) {
cout << "Invalid age!";
} else {
cout << "Valid age: " << age;
}
Validation Techniques
Number Validation
Check if input is valid number
if (cin.fail()) {
cout << "Invalid number!";
}
Range Validation
Check if values are in range
if (age < 0 || age > 120) {
cout << "Age out of range!";
}
String Validation
Validate text input
if (name.empty()) {
cout << "Name cannot be empty!";
}
Input Loops
Keep asking until valid input
while (cin.fail()) {
cin.clear();
cin.ignore(1000, '\n');
}
🔹 Basic Number Validation
Validating numeric input prevents errors and ensures data integrity. The process involves reading user input as a string, attempting conversion to a target numeric type (e.g., int, double), and catching conversion failures. Providing clear, immediate feedback on invalid input (like non-numeric characters) creates a robust user experience. This foundational validation is a critical first step before any arithmetic operations or business logic to avoid crashes, exceptions, or incorrect computations.
#include <iostream>
#include <limits>
using namespace std;
int getValidInteger(const string& prompt) {
int number;
while (true) {
cout << prompt;
cin >> number;
// Check if input failed (non-numeric input)
if (cin.fail()) {
cout << "Error: Please enter a valid integer!" << endl;
// Clear the error flag
cin.clear();
// Ignore the invalid input
cin.ignore(numeric_limits<streamsize>::max(), '\n');
} else {
// Clear any remaining characters in buffer
cin.ignore(numeric_limits<streamsize>::max(), '\n');
return number;
}
}
}
int main() {
int age = getValidInteger("Enter your age: ");
int score = getValidInteger("Enter your score: ");
cout << "Age: " << age << ", Score: " << score << endl;
return 0;
}
Output (with invalid input):
Enter your age: abc
Error: Please enter a valid integer!
Enter your age: 25
Enter your score: 95
Age: 25, Score: 95
🔹 Range Validation
Range validation ensures numbers fall within acceptable minimum and maximum bounds. After successful numeric conversion, the value is checked against predefined limits (e.g., age between 0 and 120). This guards against logically impossible or dangerous inputs. Custom validation logic can also enforce steps (multiples of a number) or discrete sets of allowed values. Implementing range checks is essential for configuration settings, game logic, scientific parameters, and any domain where values have physical or logical constraints.
#include <iostream>
using namespace std;
int getAgeInRange() {
int age;
do {
cout << "Enter age (0-120): ";
cin >> age;
if (cin.fail()) {
cout << "Error: Please enter a number!" << endl;
cin.clear();
cin.ignore(1000, '\n');
age = -1; // Force loop to continue
} else if (age < 0 || age > 120) {
cout << "Error: Age must be between 0 and 120!" << endl;
}
} while (age < 0 || age > 120);
return age;
}
double getGradeInRange() {
double grade;
do {
cout << "Enter grade (0.0-100.0): ";
cin >> grade;
if (cin.fail()) {
cout << "Error: Please enter a number!" << endl;
cin.clear();
cin.ignore(1000, '\n');
grade = -1; // Force loop to continue
} else if (grade < 0.0 || grade > 100.0) {
cout << "Error: Grade must be between 0.0 and 100.0!" << endl;
}
} while (grade < 0.0 || grade > 100.0);
return grade;
}
int main() {
int age = getAgeInRange();
double grade = getGradeInRange();
cout << "Valid age: " << age << endl;
cout << "Valid grade: " << grade << endl;
return 0;
}
Output:
Enter age (0-120): 150
Error: Age must be between 0 and 120!
Enter age (0-120): 25
Enter grade (0.0-100.0): 95.5
Valid age: 25
Valid grade: 95.5
🔹 String Validation
String validation enforces text input requirements like length, format, and content. Common checks include minimum/maximum length, allowed character sets, regex pattern matching (for emails, phone numbers), and the absence of forbidden substrings. Validation should occur early, ideally before storage or processing, to maintain data quality and security. Effective string validation prevents database errors, injection attacks, and ensures that downstream systems receive clean, well-structured textual data.
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
bool isValidName(const string& name) {
if (name.empty()) {
cout << "Error: Name cannot be empty!" << endl;
return false;
}
if (name.length() < 2) {
cout << "Error: Name must be at least 2 characters!" << endl;
return false;
}
// Check if name contains only letters and spaces
for (char c : name) {
if (!isalpha(c) && c != ' ') {
cout << "Error: Name can only contain letters and spaces!" << endl;
return false;
}
}
return true;
}
bool isValidEmail(const string& email) {
if (email.empty()) {
cout << "Error: Email cannot be empty!" << endl;
return false;
}
// Simple email validation
size_t atPos = email.find('@');
size_t dotPos = email.find('.', atPos);
if (atPos == string::npos || dotPos == string::npos || atPos == 0 || dotPos == email.length() - 1) {
cout << "Error: Invalid email format!" << endl;
return false;
}
return true;
}
string getValidName() {
string name;
do {
cout << "Enter your name: ";
getline(cin, name);
} while (!isValidName(name));
return name;
}
string getValidEmail() {
string email;
do {
cout << "Enter your email: ";
getline(cin, email);
} while (!isValidEmail(email));
return email;
}
int main() {
cout << "User Registration" << endl;
cout << "=================" << endl;
string name = getValidName();
string email = getValidEmail();
cout << "\nRegistration successful!" << endl;
cout << "Name: " << name << endl;
cout << "Email: " << email << endl;
return 0;
}
Output:
User Registration
=================
Enter your name: J
Error: Name must be at least 2 characters!
Enter your name: John Doe
Enter your email: invalid-email
Error: Invalid email format!
Enter your email: [email protected]
Registration successful!
Name: John Doe
Email: [email protected]
🔹 Menu Choice Validation
Menu choice validation confirms user selections correspond to available options. After displaying a menu, the program prompts for a numeric or character choice. Validation involves checking that the input is a valid type and that its value maps to an existing menu item. This creates a fault-tolerant interface, gracefully reprompting on invalid input without crashing. It's a key component of CLI applications, games, and any interactive system where user navigation must be reliable and intuitive.
#include <iostream>
using namespace std;
int getMenuChoice() {
int choice;
cout << "\n=== MAIN MENU ===" << endl;
cout << "1. View Profile" << endl;
cout << "2. Edit Settings" << endl;
cout << "3. View Reports" << endl;
cout << "4. Exit" << endl;
cout << "=================" << endl;
do {
cout << "Enter your choice (1-4): ";
cin >> choice;
if (cin.fail()) {
cout << "Error: Please enter a number!" << endl;
cin.clear();
cin.ignore(1000, '\n');
choice = 0; // Invalid choice to continue loop
} else if (choice < 1 || choice > 4) {
cout << "Error: Please choose between 1 and 4!" << endl;
}
} while (choice < 1 || choice > 4);
return choice;
}
char getYesNoChoice(const string& question) {
char choice;
do {
cout << question << " (y/n): ";
cin >> choice;
choice = tolower(choice);
if (choice != 'y' && choice != 'n') {
cout << "Error: Please enter 'y' for yes or 'n' for no!" << endl;
}
} while (choice != 'y' && choice != 'n');
return choice;
}
int main() {
bool running = true;
while (running) {
int choice = getMenuChoice();
switch (choice) {
case 1:
cout << "Viewing profile..." << endl;
break;
case 2:
cout << "Editing settings..." << endl;
break;
case 3:
cout << "Viewing reports..." << endl;
break;
case 4:
char confirm = getYesNoChoice("Are you sure you want to exit?");
if (confirm == 'y') {
running = false;
cout << "Goodbye!" << endl;
}
break;
}
}
return 0;
}
Output:
=== MAIN MENU ===
1. View Profile
2. Edit Settings
3. View Reports
4. Exit
=================
Enter your choice (1-4): 5
Error: Please choose between 1 and 4!
Enter your choice (1-4): 1
Viewing profile...
🔹 Input Validation Best Practices
Effective input validation combines clarity, security, and user experience. Best practices include validating on the server-side (defense in depth), providing immediate, specific error messages, and using allow-lists over deny-lists. Sanitize input for the specific context (e.g., SQL, HTML). Avoid revealing system internals in errors. Implement validation as early as possible in the data pipeline. These strategies collectively reduce bugs, prevent security vulnerabilities like injection attacks, and guide users to provide correct data efficiently.
Validation Strategies:
- Always validate user input - Never trust user data
- Provide clear error messages - Tell users what went wrong
- Give examples - Show users the expected format
- Handle edge cases - Empty strings, very large numbers, etc.
- Use loops for retry - Keep asking until valid input
Common Validation Checks:
- Type checking - Is it a number, string, etc.?
- Range checking - Is the value within acceptable limits?
- Format checking - Does it match expected pattern?
- Length checking - Is the string too short or too long?
- Character checking - Contains only allowed characters?
Error Handling:
- cin.fail() - Check if input operation failed
- cin.clear() - Clear error flags
- cin.ignore() - Skip invalid characters
- getline() - Better for string input with spaces