Joshua
Joshua

Reputation: 4320

Multiple inputs on one line

I have looked to no avail, and I'm afraid that it might be such a simple question that nobody dares ask it.

Can one input multiple things from standard input in one line? I mean this:

float a, b;
char c;

// It is safe to assume a, b, c will be in float, float, char form?
cin >> a >> b >> c;

Upvotes: 47

Views: 232874

Answers (3)

Patrick Cyubahiro
Patrick Cyubahiro

Reputation: 109

Yes, it is absolutely right to consider that variables a, b, and c are within the float, float, and char data types - just as specified.

To make it easier to read, I would suggest adding some space between the variables, in the output (cout<<).

For example, you could try something like this: cout<<"The alphanumeric elements entered are as follows: "<< a << " " << b << " " << c <<endl;

As far as inputting multiple items on a single line: yes, it is absolutely possible.

All of the below three can work:

cin >> a; 
cin >> b; 
cin >> c;

cin >> a >> b >> c ;

cin >> a ; cin >> b ; cin >> c ;

Upvotes: 0

Jeremy
Jeremy

Reputation: 108

Yes, you can.

From cplusplus.com:

Because these functions are operator overloading functions, the usual way in which they are called is:

   strm >> variable;

Where strm is the identifier of a istream object and variable is an object of any type supported as right parameter. It is also possible to call a succession of extraction operations as:

   strm >> variable1 >> variable2 >> variable3; //...

which is the same as performing successive extractions from the same object strm.

Just replace strm with cin.

Upvotes: 9

Robᵩ
Robᵩ

Reputation: 168886

Yes, you can input multiple items from cin, using exactly the syntax you describe. The result is essentially identical to:

cin >> a;
cin >> b;
cin >> c;

This is due to a technique called "operator chaining".

Each call to operator>>(istream&, T) (where T is some arbitrary type) returns a reference to its first argument. So cin >> a returns cin, which can be used as (cin>>a)>>b and so forth.

Note that each call to operator>>(istream&, T) first consumes all whitespace characters, then as many characters as is required to satisfy the input operation, up to (but not including) the first next whitespace character, invalid character, or EOF.

Upvotes: 51

Related Questions