News:

This week IPhone 15 Pro winner is karn
You can be too a winner! Become the top poster of the week and win valuable prizes.  More details are You are not allowed to view links. Register or Login 

Main Menu

C++ Tips:IO - Mixing item-oriented versus line-oriented reading

Started by ben2ong2, October 06, 2006, 11:15:13 PM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

ben2ong2

RESPONSE: You are not allowed to view links. Register or Login (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: You are not allowed to view links. Register or Login (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.




You are not allowed to view links. Register or Login
You are not allowed to view links. Register or Login