从c++中声明的输入中读取
Read from input in a declaration in C++?
我来自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;
}
相关文章:
- 读取文件并输入到矢量中
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 如何在C++中读取空格分隔的输入 当我们不知道输入的数量时
- 套接字读取后,我在缓冲区中看到意外输入
- 从标准输入读取文件后读取用户输入
- C++ 从标准输入读取文件名
- 从标准输入读取多个类型时出现问题
- 使用 fgets() 从键盘读取时从以前的输入读取换行符
- 从标准输入读取时zmq_poll不侦听信号
- 从超强的AndroidAudioIO输入读取缓冲区
- 如何实现将用户输入读取到提供的所有变量中的可变参数模板
- 如何使用重定向的标准输入读取文件,即cin(注意:不使用ifstream)
- 将空格分隔的输入读取到C++中的数组中
- Win32 - 从标准输入读取超时
- 从标准输入读取输入,并准备接收来自服务器的广播
- 终止将输入读取到int中的内容
- 如何从标准输入读取输入,直到按下空格或选项卡
- DirectX 11输入读取方法
- 将输入读取到动态大小的数组中