views:

79

answers:

2

hey, i'm a noob to c++ (and coding in general) i'm looking for an easy way to take two doubles (at once) from the keyboard and store them in a struct i've created called "Point" and then ultimately store the Point into a vector of Points that's a member of a class (called "Polygon"). i know i could do it with a scanf but need to know how to do it with cin.

hope that makes sense.

thanks in advance

julz

+2  A: 

You can do:

double d1,d2;
cin>>d1>>d2;

or you can directly read it into your structure variable as:

point p;
cin>>p.x>>p.y;

assuming your structure is defined something like:

struct point {
 double x;
 double y;
}
codaddict
really? and does the input need to be separated by a comma or just a space?
Julz
Whitespace not comma
KTC
Yeah, operator>> is your friend in C++.
Justin Ardini
yeah nice,that's awesome thanks heaps!
Julz
oh, do i need to mark this question as answered?
Julz
@julz666: No, but it'll sure go a long way toward getting more answers in the future...
Billy ONeal
so i just click the tick?
Julz
can you do formatted input with commas this way?
Aran Mulholland
you do just click the tick
Aran Mulholland
+3  A: 

An alternative is to overload >> so that it operates on your structure directly:

struct Point {
    int x;
    int y;

    friend std::istream& operator >>(std::istream& stream, Point& p) {
        return stream >> p.x >> p.y;
    }
}

You return the stream so that you can chain inputs the same way you can with built in types: cin >> p1 >> p2 >> p3. In this specific case, the operator could be a freestanding function, rather than a friend, but in general a friend is easier to work with.

This provides a lot of useful details on this sort of thing.

Dennis Zickefoose
yeah, i think that's what our lecturer was getting at. i'll do some work on that, thanks
Julz