从c++中声明的输入中读取

Read from input in a declaration in C++?

本文关键字:输入 读取 声明 c++      更新时间:2023-10-16

我来自Java在使用扫描器时可以做这样的事情

int n = s.nextInt();

现在我开始使用c++了,我发现这样做很烦人:

int n;
cin >> n;

是否有一种从变量声明中读取输入的快捷方式?

您可以创建一个辅助函数来为您做这件事:

// 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>();
...

但是,此时,您可能希望查找已经完成此操作的现有库。

没有内置的快捷方式,但是您当然可以为此创建自己的函数:

int read_int() {
    int res;
    cin >> res;
    return res;
}
...
int a = read_int();

使用模板使dasblinkenlight和Michael Aaron Safyan建议的函数更通用(现在并入Michael回答的最后示例中):

#include <iostream>
template<typename T> T read();
template<typename T>
T read<T>() {
    T ret;
    std::cin >> ret;
    return ret;
}
int main() {
    int i = read<int>();
    double d = read<double>();
    std::cout << i << std::endl << d;
    return 0;
}