简体   繁体   中英

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. 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.

There is not. All standard input interfaces take an object argument which they modify rather than return the resulting value 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). 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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