Secure input in C++

In your programs, it might be needed to request information from the user. In C++ the information is collected using "cin" object. If you do not secure these inputs, then your program is likely to be the victim of a "buffer overflow". Indeed, if the number of characters entered exceeds the buffer size originally planned, then the last data overwrites other data on the stack, and erroneous data affect the ESP and EBP registers.

You can secure these data input in different ways.

Using the get() method

#include int main() { char texte[100]; cin.get(texte, 100); //premier paramètre : la où va la saisie second : taille max de saisie return 0; }

This example illustrates the use of cin.get.

If the text entered exceeds the allocated size, the extra characters are ignored.

Using the "getline ()" method

This method works like get(), but it removes the character at the end of the buffer.

Indeed, to validate a text, the user presses the "Enter" key, which corresponds to the '

' character.

getline() removes this character.

==It does not work!!===

Here's a code that does not work properly:

#include using namespace std; int main() { char entree[100]; int choix; cout << "Entrez un nombre :" ; cin >> choix; cout << "Entrez un texte : "; cin.get(texte, 100); cout << "Saisies terminées !"; return 0; }

Indeed, the second entry is not executed, and the message "Input done!/Saisies terminées !"" appears.

How to solve this problem?

You must use the "ignore()" method.

The ignore() method

This method allows to ignore certain characters in a string.

#include using namespace std; int main() { char entree[100]; int choix; cout << "Entrez un nombre :" ; cin >> choix; cout << "Entrez un texte : "; cin.ignore(1, '

'); //ignore le caractère d'entrée, qui validait auparavant la saisie. cin.get(texte, 100); cout << "Saisies terminées !"; return 0;

With this method, the input character is ignored, and the problem solved.

Spread the love

Leave a Comment