istream Input

Requires #include <istream> ; or #include <iostream> preprocessor directive.

 

The extraction operator >> is used to read information from the input stream.

 

Can be overloaded for specific purposes (e.g. for an object of a specific class data type).

 

A few problems may arise that can overcome by the use of manipulators:

  • endl - (in iostream) prints new line and flushes any buffered output
  • setw() - (in iomanip) limits number of characters being read
  • getch() - gets a character from the input stream (including whitespace)
  • getline() - as above but also gets the newline
  • gcount() - returns the numbers of characters read
  • ignore() discards the first character in the stream
  • ignore(number) discards the first specified 'number' parameter of characters
  • peek() allows you to read a character from the stream without removing it from the stream
  • unget() returns the last character read back into the stream so it can be read again by the next call
  • putback(character) allows you to put the specified character parameter of your choice back into the stream to be read by the next call
#include <iostream>
#include <iomanip>
using namespace std;

int main () {

	cout << "Please enter the first three characters of your name:" << endl ;

	char name[3];

	cin >> std::setw(3) >> name ;

	cout << "Notice that a null terminator has taken the last position in the char array, " << endl ;
	cout << "thus only returning the first two characters: "<< name << endl ;

	return 0;
}

Compile & Run:

Please enter the first three characters of your name:
Der
Notice that a null terminator has taken the last position in the char array,
thus only returning the first two characters: De

 

 

Using getline() to get the whole line including whitespace:

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

int main () {

	string myString;

	cout << "Please enter an you full name: " << endl ;

	getline(cin, myString) ;

	cout << "Hi " << myString << "!" << endl ;
	cout << "What's the first line of your address?" << endl ;

	getline(cin, myString) ;

	cout << "Thanks for confirming " << myString << " as your address." << endl ;

	return 0;
}
Please enter an you full name:
Andrea Dovizioso
Hi Andrea Dovizioso!
What's the first line of your address?
21 Coconut Grove
Thanks for confirming 21 Coconut Grove as your address.

Leave a Reply