Listing 4.6 illustrates a problem created by following numeric input with line-oriented string input. How would replacing

Question:

Listing 4.6 illustrates a problem created by following numeric input with line-oriented string input. How would replacing this:
cin.getline(address,80);
with this:
cin >> address;
affect the working of this program?

Running the program in Listing 4.6 would look something like this:
What year was your house built?
1966
What is its street address?
Year built: 1966
Address
Done!
You never get the opportunity to enter the address. The problem is that when cin reads the year, it leaves the newline generated by the Enter key in the input queue. Then
cin.getline() reads the newline as an empty line and assigns a null string to the address array. The fix is to read and discard the newline before reading the address. This
can be done several ways, including by using get() with a char argument or with no argument, as described in the preceding example. You can make these calls separately:
cin >> year;
cin.get(); // or cin.get(ch);
Or you can concatenate the calls, making use of the fact that the expression
cin >> year returns the cin object:
(cin >> year).get(); // or (cin >> year).get(ch);
If you make one of these changes to Listing 4.6, it works properly:
What year was your house built?
1966
What is its street address?
43821 Unsigned Short Street
Year built: 1966
Address: 43821 Unsigned Short Street
Done!
C++ programs frequently use pointers instead of arrays to handle strings. We’ll take up that aspect of strings after talking a bit about pointers. Meanwhile, let’s take a look at a more recent way to handle strings: the C++ string class.

Fantastic news! We've Found the answer you've been seeking!

Step by Step Answer:

Related Book For  answer-question

C++ Primer Plus

ISBN: 9780321776402

6th Edition

Authors: Stephen Prata

Question Posted: