Вы можете просто сделать вспомогательную функцию, чтобы сделать это для вас:
// Using an anonymous namespace, since this is intended to
// be just an internal utility for your file... it's not
// a super awesome, shareable API (especially since it hard
// codes the use of std::cin and has no error checking).
namespace {
// Helper function that reads an integer from std::cin.
// As pointed out in Robin's solution, you can use a template
// to handle other types of input, as well.
int ReadInt() {
int result;
std::cin >> result;
return result;
}
}
Тогда вы можете сделать:
int n = ReadInt();
Если вы действительно хотите идти на все, хотя, вы можете создать более сложное решение:
namespace input_utils {
class IOException {};
class Scanner {
public:
Scanner() : input_(std::cin) {}
Scanner(std::istream& input) : input_(input) {}
template<typename T> T Read() {
CheckStreamOkay();
T result;
input_ >> result;
CheckStreamOkay();
return result;
}
private:
void CheckStreamOkay() {
if (!input_) {
throw IOException();
}
}
std::istream& input_;
};
}
Затем вы можете сделать что-то вроде:
input_utils::Scanner scanner(std::cin);
int a = scanner.Read<int>();
int b = scanner.Read<int>();
double c = scanner.Read<double>();
...
Хотя в этот момент вам может потребоваться найти существующую библиотеку, которая уже делает это.
Как бы вам не понадобилось –
Проводили ли пробелы в вашем сокращении? –