所以我從Java未來在這裏你可以使用掃描儀從輸入中讀取C++中的聲明?
int n = s.nextInt();
現在,我與C++涉足時做這樣的事情,我覺得很討厭的事:
int n;
cin >> n;
有沒有簡單的方法來讀取變量聲明中的輸入?
所以我從Java未來在這裏你可以使用掃描儀從輸入中讀取C++中的聲明?
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>();
...
雖然在這一點上,你可能想要尋找一個已經做到這一點的現有庫。
要模擬Java行爲,您應該在失敗時拋出異常。或者你應該至少有*某種方式來表明這裏的失敗。 –
@BenjaminLindley如果我們真的要模擬Java行爲,那麼我們應該有一個包裝器「掃描器」類,它應該採用任意「std :: istream」作爲輸入,而不是嚴格的std :: cin。我同意你的意思,但是OP只是簡單地詢問語法的簡單性(而且給出的例子也沒有做任何檢查)。這立即解決了OP的難點,但你說得對,這需要很多改進才能成爲一個好的API。 –
很好的例子把這些答案放在一起。 +1 –
有沒有內置的快捷方式,但你當然可以彌補這方面自己的函數:
int read_int() {
int res;
cin >> res;
return res;
}
...
int a = read_int();
製作使用模板(由dasblinkenlight和邁克爾·亞倫Safyan更通用的建議的功能現已併入邁克爾的回答的最後一個例子):
#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;
}
如何短,你需要做 –
計數的空間在你的速記? –