Home Programming C++ Input Example w/Buffer Protection

Search

C++ Input Example w/Buffer Protection Print
Written by Chris Gountanis   

This program demonstrates input with buffer limits using C++.

 

 

 

 

#include <iostream>

 

 

using namespace std;

 

 

void main() {

 

 

// NUMBER OF CHAR LIMIT (ADD ONE TO ACTUAL NUMBER - REMEMBER CIN RESERVES ONE SPACE)

const int char_limit = 5;

char inputbuffer[char_limit] = {0};

 

 

// PRINT MESSAGE TO SCREEN ASKING USER FOR INPUT

cout << "ENTER LINE (only " << char_limit << " char will be allowed)\n>";

 

 

// GET USER INPUT UP TO LIMIT

cin.getline(inputbuffer, char_limit);

 

 

// IF LIMIT WAS EXCEEDED RESET CIN AND REMOVE LINE RETURN

if(cin.fail()) {

cin.clear();

cin.ignore(INT_MAX, '\n');;

}

 

 

// OUTPUT RESULTS TO SCREEN

cout << inputbuffer << endl;

 

 

//WAIT FOR USER TO PRESS ENTER

cout << "\nPress ENTER to continue.";

cin.get();

}

Last Updated on Saturday, 09 February 2008 21:02