Programming and Graphics

(Kiana) #1

60 Introduction to C++ Programming and Graphics


Leading white space generated by the space bar, the tab key, and the
carriage return is ignored by thecinfunction.


Now consider the following block of commands:

double pi;
int a;
cin >> pi;
cin >> a;

Suppose that, on execution, we enter the numberπin segments separated by
white space:


3.14159 265358

Since the twocinstatements are equivalent to:


cin >> pi >> a;

the program will take


pi=3.14159 a=265358.

Thus, the computer will not pause for the secondcin, giving the false im-
pression of a coding error.


In professional codes, we circumvent this difficulty by reading all input
date as strings, and then making appropriate data type conversions.


Receiving a string


To read a string variable from the keyboard, we use:

cin >> astring;

The string variableastringin this statement is not allowed to have any
blank spaces; that is, it cannot be a sentence composed of words. To circumvent
this difficulty, we use instead:


getline(cin, astring);

On execution, the computer will wait for a string to be typed in the keyboard,
followed by theEnterkeystroke.

Free download pdf