Ryan's District Boards

Computer, programming, and webmaster help , support , tips and tricks => Tutorials Zone! => Internet webmaster computer programming technology tips and tricks => C++ / C / C# ....Tutorials => Topic started by: ben2ong2 on October 06, 2006, 11:15:13 PM

Title: C++ Tips:IO - Mixing item-oriented versus line-oriented reading
Post by: ben2ong2 on October 06, 2006, 11:15:13 PM
RESPONSE: rlogan@axysdev.nwest.mccaw.com (Ron Logan)

Well, since you're leaning C++, forget scanf -- that's yucky C stuff.  If 
you're going to learn "C++", you should use the stream library (cin, cout, 
etc.).
Try this:

//Program
#include <iostreams.h>

void main( void )
{
    char name[20];
    char comment[20];
    int age;

    cout << "What is your first name? ";
    cin >> name;
    cout << "What is your age? ";
    cin >> age;
    cout << "Leave a short comment:" << endl;
    cin.getline( comment, sizeof(comment) );

    cout << "Your first name is " << name << endl;
    cout << "You are " << age << " years old." << endl;
    cout << "You comment was " << comment << endl;
}


RESPONSE: clamage@Eng.Sun.COM (Steve Clamage), 10 Aug 94

Too bad Ron posted this "solution" without trying it.

Typo's aside, this program has exactly the same error as the
version using scanf and gets: After asking for a comment, the program
immediately produces its final output before you have a chance to
enter a comment.

The difficulty is combining code which gets an item at at time, like
'scanf("%d", &age)' or 'cin >> age', with code which gets a line at
a time, like 'gets' or 'getline'.

The item-at-a-time code skips leading whitespace and leaves trailing
whitespace in the input stream. Whitespace includes newline characters.
When you enter data from the keyboard, it is terminated by a newline.

The line-at-a-time code does not skip leading whitespace, and reads up to
the next newline character.

After getting the age, the trailing newline is left in the input. When
reading the "next" line, you in fact read what is left on the old line.
That is just a plain newline, considered an empty line of text.

Switching from item to line input is tricky, since you first must consume a
trailing newline if and only if there is a trailing newline. In this
case there will be, so you should discard the remainder of the line on
which 'age' appeared before asking for a comment. This is true in both
the scanf/gets version and the version shown here.