From a9b58871c077ecd1e161fd818b40dd406a3914d2 Mon Sep 17 00:00:00 2001 From: Captain ALM Date: Fri, 26 Aug 2022 12:10:43 +0100 Subject: [PATCH] Test loop and input error checking 2. Fix issue with error checking. --- main.cpp | 33 ++++++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/main.cpp b/main.cpp index 33a48c8..cb2464a 100644 --- a/main.cpp +++ b/main.cpp @@ -3,11 +3,19 @@ using string = std::string; void ignoreTillLineEnd(); string promptfs(string); +int promptfi(string); int main() { - string name {promptfs("Enter your name:")}; - std::cout << "Hello " << name << "\n"; + int nameC {promptfi("Enter the number of names:")}; + if (nameC < 1) { + std::cout << "No names to be entered!\n"; + return 1; + } + string* names = new string[nameC]; + for (int i = 0; i < nameC; i++) names[i] = promptfs("Enter your name:"); + std::cout << "I have " << nameC << " to say hello to!\n"; + for (int i = 0; i < nameC; i++) std::cout << "Hello " << names[i] << ".\n"; return 0; } @@ -21,13 +29,32 @@ string promptfs(string msg) { do { if (once) { std::cin.clear(); + ignoreTillLineEnd(); std::cout << "Input Failure!\n"; } std::cout << msg << "\n"; std::cin >> toret; - ignoreTillLineEnd(); once = true; } while (std::cin.fail()); + ignoreTillLineEnd(); + return toret; +} + +int promptfi(string msg) { + bool once {false}; + int toret {}; + do { + if (once) { + std::cin.clear(); + ignoreTillLineEnd(); + std::cout << "Input Failure!\n"; + } + std::cout << msg << "\n"; + std::cin >> toret; + once = true; + } + while (std::cin.fail()); + ignoreTillLineEnd(); return toret; }