简体   繁体   English

在 C++ 中返回输入

[英]Returning input in C++

I'm very new to C++ and was wondering if there was a way to return integer input from a function directly without storing it in a variable.我对 C++ 很陌生,想知道是否有办法直接从 function 返回 integer 输入而不将其存储在变量中。 To be more clear:更清楚地说:

#include <iostream>

int function()
{
    std::cin >> (return function here???)
}
int main()
{
    int number = function()
    std::cout << number
    return 0;
}

Thanks for any help.谢谢你的帮助。

if there was a way to return integer input from a function directly without storing it in a variable.如果有办法直接从 function 返回 integer 输入而不将其存储在变量中。

There is not.那没有。 All standard input interfaces take an object argument which they modify rather than return the resulting value 1 .所有标准输入接口都采用 object 参数,它们修改而不是返回结果值1

A possible reason for this design is that it is very typical for input to be bad.这种设计的一个可能原因是输入错误是非常典型的。 Only way to avoid returning an int from a function declared to return int is to throw (or terminate the process, but that would be silly).避免从声明返回int的 function 返回int的唯一方法是抛出(或终止进程,但这很愚蠢)。 And input error is perhaps considered so non-exceptional that using exceptions for control flow of input handling may be considered inappropriate.并且输入错误可能被认为是非异常的,以至于使用异常来处理输入处理的控制流可能被认为是不合适的。 This is just my reasoning, not an authoritative explanation for the design choice.这只是我的推理,不是设计选择的权威解释。

If you fix your function to be correct, with the variable that is necessary and checking for errors, then you can use that function to do exactly that:如果您修复您的function是正确的,使用必要的变量并检查错误,那么您可以使用 function 来做到这一点:

return function();

1 With the exception of std::istream::get() and the corresponding C style std::getc and std::fgetc which you can use to extract a single character that they return directly. 1除了std::istream::get()和相应的 C 样式std::getcstd::fgetc之外,您可以使用它们来提取它们直接返回的单个字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM