8.3.1. string Class I/O

Time: 00:01:53 | Download: Large, Large (CC), Small | Streaming, Streaming (CC) | Slides (PDF)

Previously, we explored the behavior of C-string console I/O. We discovered that the inserter operator, <<, worked well for C-string output. However, the extractor operator, >>, didn't work reliably for C-string input. Specifically, the extractor fails to read white space (spaces and tabs). You should note that this behavior results from the operators and not the kind of string used.

The following program repeats the simple program used to demonstrate the failure of the extractor when used with C-strings but with a string object as the target:

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

int main()
{
	string	input;

	//cin >> input;			// stops reading at space
	//cout << input << endl;	
	getline(cin, input);		// discards \n
	cout << input << endl;


	return 0;
}
string object I/O example. The extractor operator, >>, again fails to read spaces into a string object just as it failed to read spaces into a C-string. In the earlier C-string example, we solved the problem with a function named getline, and we'll take the same approach here. But notice that we're using a different getline function here despite having the same name.

The following figure compares the two getline functions side by side to highlight their differences.

C-Stringstring Class
char input[100];
cin.getline(input, 100);
string input;
getline(cin, input);
cin
The input stream from which the data is read
100
The size of the character array storing the C-string
input
The name of the C-string. The function saves the string read from the console in this variable
cin
The input stream from which the data is read
input
The name of the string object. The string read from the console is stored in this object
C-string getline vs. string class getline. Both kinds of strings have a getline function that can read spaces embedded in strings. But they are different functions with different argument lists.