I am learning about buffer overflows and want to know what is the best way to prevent a user from entering more characters than is allowed and causing a buffer overflow.
What are the best practices to prevent buffer overflows?
Here is my code:
#include <iomanip>
#include <iostream>
int main()
{
std::cout << "Buffer Overflow Example" << std::endl;
// The user can type more than 20 characters and overflow the buffer, resulting in account_number being replaced -
// even though it is a constant and the compiler buffer overflow checks are on.
// I need to modify this method to prevent buffer overflow without changing the account_order
// varaible, and its position in the declaration. It must always be directly before the variable used for input.
const std::string account_number = "CharlieBrown42";
char user_input[20];
std::cout << "Enter a value: ";
std::cin >> user_input;
std::cout << "You entered: " << user_input << std::endl;
std::cout << "Account Number = " << account_number << std::endl;
}