Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple inputs on one line

Tags:

c++

input

cin

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; 
like image 822
Joshua Avatar asked Sep 15 '11 02:09

Joshua


People also ask

How do you take multiple inputs in one line?

In C++/C user can take multiple inputs in one line using scanf but in Python user can take multiple values or inputs in one line by two methods. Using split() method : This function helps in getting multiple inputs from users. It breaks the given input by the specified separator.

How do you take a list of inputs in one line?

To take list input in Python in a single line use input() function and split() function. Where input() function accepts a string, integer, and character input from a user and split() function to split an input string by space.

How do you take n number inputs in one line in Python?

You can use a list comprehension to take n inputs in one line in Python. The input string is split into n parts, then the list comp creates a new list by applying int() to each of them.


2 Answers

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.

like image 177
Robᵩ Avatar answered Sep 19 '22 20:09

Robᵩ


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.

like image 28
Jeremy Avatar answered Sep 23 '22 20:09

Jeremy