Text Input
2002-06-12 02:10:30
Category: cpp:input
Description: Read text in from the console using cin.getline, cin.get and cin.read to avoid buffer overflows caused by no bounds checking.
Author: detour
Viewed: 4497
Rating: (15 votes)


/* cinget.cpp by detour@metalshell.com 
 *
 * Shows how to read in text from the console.  Using
 * a normal cin will lead to buffer overflows.
 *
 * http://www.metalshell.com/
 *
 */
 
#include <iostream.h>
#include <string.h> 
 
int main() {
    char line[16];
 
 
    /* reads in from the console until a '\n' is found. */
    cout << "Enter any text: ";
    cin.getline(line,sizeof(line));
    cout << "line = " << line << endl;
    /* reads in from the console until a 'A' is found. */
    cout << "End text with an 'A': ";
    cin.getline(line,sizeof(line),'A');
    cout << "line = " << line << endl;
    /* if you use a different dilimiter you must get rid
       of the newline character yourself */
    cin.get();
    
 
    /* unlike getline(), get() will not discard the delimiter */
    cout << "End text with an 'A': ";
    cin.get(line,sizeof(line),'A');
    cin.get(); cin.get();
    cout << "line = " << line << endl;
    cout << "Enter any text: ";
    cin.get(line,sizeof(line));
    cout << "line = " << line << endl;
    cin.get();
 
    /* read() will not insert a '' at the end of the string,
       and does not have the delimiter option, input will be read
       until buffer is filled followed by an enter */
    cout << "Enter any text: ";
    cin.read(line,sizeof(line));
    line[sizeof(line)] = '\0';
    cout << "line = " << line << endl;
    cin.clear();
 
    return 0;
}