如何在没有任何变量的情况下从控制台读取数字

How to read number from a console without any variables

我知道要从控制台读取我们可以使用

int number;
cin >> number;
//A line of code where we use int number

但是是否可以在没有任何变量的情况下从控制台读取数字。是否有任何方法 return 来自控制台的数字?

getchar() 函数允许您忽略一个字符,而不是使用变量来保存值。

But is it possible to read a number from console without any variables.

不使用任何变量读取数字 – 听起来像个谜。

我们开始:

#include <iostream>

int main()
{
  return !std::cin.operator>>(*new int());
}

这个节目returns

  • 0 …成功(输入一个数字)
  • 1 … 出错(输入的不是数字)。

输出:

Test 123:
Error: 0
Test abc:
Error: 1

Live Demo on coliru

注:

我不得不为流输入运算符提供一个临时的 LValue。 我没有比 *new int() 更好的主意,尽管我知道这会导致内存泄漏。 在这个简单的程序中,这不会造成伤害,因为 OS 将为我生成 clean-up。


Are there any methods that return a number from console?

这部分我真的不清楚。

如果我自己遇到这个问题,我会做一个辅助函数

int readNum(std::istream &in)
{
  int number; in >> number; return number;
}

然后我可以在没有任何变量的 main() 函数中使用它

int main()
{
  std::cout << "Number: " << readNum(std::cin) << '\n';
}

但是readNum()不得不再次使用变量来存储格式化输入的结果。

如果要再次访问输入结果,则很难使用没有任何变量的格式化输入流运算符(至少,在仅具有 std 库的 C++ 中)。