我希望在 C 中創建這個函式,input("x = ");,有點像在 python 中,這個函式在 () 中列印訊息并期望輸入。它只能采用bool、str、int、double。我想過像這樣進行結構輸入
struct input {
std::string str;
int num;
double dub;
bool boolean;
input(const char *s) {
std::cout << s;
std::cin >> ### ; //here is my problem
}
};
但這就是我所能得到的。我嘗試了模板,但仍然無法弄清楚。
提取輸入應該不是那么困難,我會弄清楚的,現在我只想看看如何在結構中獲取我的資料。
uj5u.com熱心網友回復:
由于型別系統根本不同,通常將 Python 翻譯成 C 是很困難的。但是,這不是問題。從檔案:
如果提示引數存在,則將其寫入標準輸出,不帶尾隨換行符。然后該函式從輸入中讀取一行,將其轉換為字串(去除尾隨的換行符),然后回傳。讀取 EOF 時,會引發 EOFError。
Pythoninput不做任何轉換。它只回傳一個字串。EOF可以啟用例外,但是當實際拋出例外時,它需要一些樣板來重置流例外設定。它可以在 RAII 類的幫助下完成,其唯一目的是重置流之前的例外設定,無論函式是回傳還是拋出。
struct eof_exception_enabled {
std::istream & inp;
std::ios::iostate old;
eof_exception_enabled(std::istream& inp) : inp(inp), old(inp.exceptions()) {
inp.exceptions(old | std::ios::eofbit);
}
~eof_exception_enabled() {
inp.exceptions(old);
}
};
std::string input(std::string prompt = "") {
std::cout << prompt;
std::string res;
auto inp = eof_exception_enabled{std::cin};
std::getline(inp.inp, res);
return res;
}
實際上,將輸入流也傳遞給input以便可以使用不同的流會更慣用。不確定這對于提示用戶并通常從標準輸入讀取的功能有多大意義。
如果要啟用轉換,可以使用利用字串流進行轉換的函式模板:
template <typename T>
T from_string(const std::string& str) {
std::stringstream ss{str};
T t;
ss >> t;
return t;
}
用法是
auto age = from_string<int>( input("enter your age:"));
但是,正確處理由于意外輸入引起的錯誤需要更多的時間。from_string僅0當從流中提取整數型別失敗時才回傳。不過,現在我們正在討論轉換,這在 Python 中也不是由input.
uj5u.com熱心網友回復:
我所做的就是上課,
template <typename T> using couple = std::pair<bool, T>;
struct input {
std::string inp;
couple<std::string> str = {false, ""};
couple<int> num = {false, 0};
couple<double> dbl = {false, 0};
couple<bool> bl = {false, 0};
input(const char *s) {
std::cout << s;
std::cin >> inp;
fillinput(inp);
}
bool check_bool(std::string inputVal) {
transform(inputVal.begin(), inputVal.end(), inputVal.begin(), ::tolower);
if (inputVal == "false") {
bl.first = true;
bl.second = false;
return true;
}
if (inputVal == "true") {
bl.first = bl.second = true;
return true;
}
return false;
}
bool check_double(std::string inputVal) {
int dots = std::count(inputVal.begin(), inputVal.end(), '.');
bool digits = std::all_of(inputVal.begin(), inputVal.end(), ::isdigit);
if (dots == 1 && digits) {
dbl.first = true;
dbl.second = std::stod(inputVal);
return true;
}
return false;
}
bool check_int(std::string inputVal) {
bool digits = std::all_of(inputVal.begin(), inputVal.end(), ::isdigit);
if (digits) {
num.first = true;
num.second = std::stoi(inputVal);
return true;
}
return false;
}
void fillinput(std::string Input) {
if (check_int(Input) || (check_bool(Input)) || (check_double(Input)))
return;
else {
str.first = true;
str.second = Input;
}
}
};
使它可用需要更多的作業,但這就是方法。我知道它的代碼不好,但它就是這樣。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/421517.html
標籤:
上一篇:你如何在C 中計算自定義資料表
