String Input with getline()

cin stops reading from the input buffer when it encounters a space.


To overcome this, the getline(source, destination) ; function is used to read the input stream from the source and store it in the specified destination, until it encounters a newline \n character (created when the user presses return).


The cin.ignore() ; function is used to ignore any content left in the input buffer.


#include <string>
#include <iostream>
using namespace std ;

int main() {
	string fullname ;		//declare the string fullname

	cout << "Please enter your full name: " << endl ;

	cin >> fullname ;

	cout << "Hi " << fullname << endl ;	// will only print the first name, up to the first space

	cout << "Please re-enter your full name: " << endl ;

	cin.ignore( 256, '\n' ) ;	// required  to overcome cin only reading up to the first space
			// leaving the second name in the input buffer
			// this specifies it should discard up to 256 characters & stop at \n

	getline ( cin, fullname ) ;	//reads text (including spaces) from cin and stores in fullname

	cout << "Thanks " << fullname << ", nice to see you!" << endl ;

	return 0 ;

Compile & Run:

Please enter your full name:
Eva Mendes
Hi Eva
Please re-enter your full name:
Eva Mendes
Thanks Eva Mendes, nice to see you!

Leave a Reply