Home
 
 
Search:  
C C++ Perl PHP Python HTML ShellScripts
 
 
  Coding Books
  Tutorials
  Search Code
  Browse Code
  Link to Us
  Site News
  Contact Metalshell
 
 
 
  Submit Code   Statistics
 



C++ Iostreams Handbook    (ISBN: 0201596415)


 

 List Price: $41.95
 Our Price: $41.95
 Used Price: $10.98

 Release Date: 30 June, 1993
 Manufacturer: Addison-Wesley Pub Co (Paperback)
 Sales Rank: 172,928

 Author: Steve Teale









More Info

 Text Input 2002-06-12 02:10:30
  cpp 
Category: source: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.
Platform: all
Author: detour
Viewed: 4229
Rating: 3.4/5 (15 votes)
If you have any questions about this piece of code or still need help, try posting your question on the forum.

 

Printable Version
cinget.cpp
/* 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 '\0' 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;
}
Rate this code:
(Not Helpful)  (Very Helpful) 

 
 
   Developer.*  
   Blue Parrots  
   Technipal  
   Defy Magazine  
   Code Project  
   Prog. Heaven  


Got Money?