Ask a question »

Secure data entry in C ++

April 2015


Secure data entry in C ++








Sometimes when creating a program, it is needed that additional information from the user must be enterd. In C++ information is collected, via the object :"cin". If you do not secure these entries, then your program is likely to be victim of a "buffer overflow".

IF the number of characters entered exceeds the buffer size originally planned, then the latest data overwrites other data on the stack and write false data to ESP and EBP registries.

Using get ()


You can secure these data entries in different ways. For example, using the member method "get ()" of the object "cin" can be a solution.
#include <iostream>

int main() {

char text[100];
cin.get(text, 100);  
return0;

}



This example illustrates the use of cin.get.
If the text entered exceeds the allocated size, the characters will be ignored too.

Using "getline ()"


This method works like get (), but it deletes the end buffer. To validate a text, the user must press the "enter" key, which corresponds to the character

'\n'. getline(), removing this character at the end of the buffer.

Remove go to newline without using getline ()


It is possible to delete the character at the end of buffer without using getline (). To do this, use the method "ignore ()" of the object "cin".

Ttwo parameters are used: the number of characters to ignore, and the end character.
If you write:
cin.ignore(12, '\n')

If the character '\ n' is in the first 12 characters of the string, it will be deleted.

It also allows you to filter the inputs, for example if you want to save a phone number, it will ignore all characters different from 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9.
For unlimited offline reading, you can download this article for free in PDF format:
Secure-data-entry-in-c.pdf

See also

In the same category

Published by jak58.
This document entitled « Secure data entry in C ++ » from Kioskea (en.kioskea.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.