Secure input in C++

December 2016




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 <iostream> 

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 '\n' character.
getline() removes this character.


==It does not work!!===
Here's a code that does not work properly:

#include <iostream> 

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 <iostream> 

using namespace std; 

int main() { 

char entree[100]; 
int choix; 
cout << "Entrez un nombre :" ; 
cin >> choix; 
cout << "Entrez un texte : "; 
cin.ignore(1, '\n');    //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.

Related :

This document entitled « Secure input in C++ » from CCM (ccm.net) is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.