C++ 一根线上有多个输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7425318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiple inputs on one line
提问by Joshua
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;
回答by Rob?
Yes, you can input multiple items from cin
, using exactly the syntax you describe. The result is essentially identical to:
是的,您可以cin
完全使用您描述的语法从 输入多个项目。结果与以下内容基本相同:
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.
每次调用operator>>(istream&, T)
(whereT
是某种任意类型) 都会返回对其第一个参数的引用。所以cin >> a
返回cin
,它可以用作(cin>>a)>>b
等等。
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.
请注意,每次调用operator>>(istream&, T)
first 都会消耗所有空白字符,然后是满足输入操作所需的字符数,直到(但不包括)第一个下一个空白字符、无效字符或 EOF。
回答by Jeremy
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 andvariable
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
.
因为这些函数是运算符重载函数,所以通常的调用方式是:
strm >> variable;
其中
strm
是 istream 对象的标识符,并且variable
是支持作为右参数的任何类型的对象。也可以将一系列提取操作称为:strm >> variable1 >> variable2 >> variable3; //...
这与从同一对象执行连续提取相同
strm
。
Just replace strm
with cin
.
只需替换strm
为cin
.