Monday, March 2, 2015

Post #2 - Last names

Images are now externally hosted on my imgur. please tell me if an image is unavailiable.

Here's a modification to the last one - what if the user wants to enter his/her last name too?

But entering a full name into the previous program results in an output problem - because cin is designed to stop when it reaches a whitespace in the input buffer, it places whatever string up until the whitespace into the variable, and leaves the rest in the input buffer. This can cause additional snafus as, when reading in multiple characters or strings, variables may not be given the full string that they are supposed to receive.

For example if I wanted to type out Have a nice day and display the entire line, there are a few options:

I would have to assign a variable to each word and show each string within a cout statement. However, since cin skips whitespace, the message all runs together.

cin >> part1 >> part2 >> part3 >> part4;
cout << part1 << part2 << part3 << part4;

The same output is also displayed when altering cout to be:
cout << part1 + part2 + part3 + part4;

in: Have a nice day
out: Haveaniceday

To fix the display, I could add spaces to the cout statement to make things look better.

cin >> part1 >> part2 >> part3 >> part4;
cout << part1 << " " << part2 << " " << part3 << " " << part4;

in: Have a nice day
out: Have a nice day

But this uses up more variables than necessary. To display everything at once using a single string variable, the full string also needs to be read into a single string variable.

We can use the function getline(a, b); to save the entire input read from a into the string variable b. getline picks up any whitespace it finds in the string, until it reaches the end of the string (marked invisibly by '\n' which is automatically appended to the end when the [Enter] key is pressed to submit the string). In most cases a will almost always be cin, as input is actually read into the standard input stream and then saved to b, an appropriate type variable, usually a string.

Now since cin is included within the getline function, the cin >> operator can be removed, since cin is already being called by the function.

getline(cin, name);

And to display the full input, just output the variable.

cout >> name;

The previous program with line 8 changed:


Here's the previous program's output when given two names:
Enter your name: Yukkuri Reimu
Hi! My name is Yukkuri.

Here's the modified version using getline, displaying both names.
Enter your name: Yukkuri Reimu
Hi! My name is Yukkuri Reimu.

For the next post, the program will read in a city and country along with the full name. This makes use of several getlines, which often run into problems with continued input. We'll see how the ignore member function can be used to keep input from becoming mixed up.

No comments:

Post a Comment