From 569d1c530c4ece04aebb9c043e2c0e23de44aa53 Mon Sep 17 00:00:00 2001 From: Matuush Date: Sun, 25 May 2025 20:25:44 +0200 Subject: [PATCH] Generalize and DRY input taking --- editor.cpp | 35 +++++++++++++---------------------- everything.hpp | 4 +++- 2 files changed, 16 insertions(+), 23 deletions(-) diff --git a/editor.cpp b/editor.cpp index a64e221..08c1e70 100644 --- a/editor.cpp +++ b/editor.cpp @@ -37,30 +37,13 @@ void Editor::print_input(string text) { ::move(cur.r, 0); adds(text); } -// Taking user input - number -count_type Editor::get_number(string prompt) { +// Generic input taking +template +string Editor::get_input(string prompt, F func) { print_input(prompt+": "); - char ch = '0'; string s = ""; - ch = getch(); - while(ch >= '0' && ch <= '9') { - s += ch; - print_input(prompt+": " + s); - ch = getch(); - } - - if(s.size() == 0) - return file_offset + cur.r; - - return stoi(s); -} -// Taking user input - string -string Editor::get_string(string prompt) { - print_input(prompt+": "); - char ch; - string s = ""; - ch = getch(); - while(ch != ENTER) { + char ch = getch(); + while((ch != ENTER && func(ch)) || ch == BS) { if(ch == BS) s.pop_back(); else @@ -70,6 +53,14 @@ string Editor::get_string(string prompt) { } return s; } +// Taking user input - string +string Editor::get_string(string prompt) { + return get_input(prompt, [](char ch) { return true; }); +} +// Taking user input - number +count_type Editor::get_number(string prompt) { + return stoi(get_input(prompt, [](char ch) { return ch >= '0' && ch <= '9'; })); +} // TODO undo diff --git a/everything.hpp b/everything.hpp index 5810126..5a7597f 100644 --- a/everything.hpp +++ b/everything.hpp @@ -103,8 +103,10 @@ class Editor{ // User input void print_input(string text); - count_type get_number(string prompt); + template + string get_input(string prompt, F func); string get_string(string prompt); + count_type get_number(string prompt); // Movement void jump_line_end();