From fb80ac50825c7ca1fa063d3493175b7b27adbdb1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gustav=20S=C3=B6rn=C3=A4s?= Date: Tue, 17 Nov 2020 15:42:27 +0100 Subject: add given code --- labb5/lib/StanfordCPPLib/simpio.cpp | 67 +++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100755 labb5/lib/StanfordCPPLib/simpio.cpp (limited to 'labb5/lib/StanfordCPPLib/simpio.cpp') diff --git a/labb5/lib/StanfordCPPLib/simpio.cpp b/labb5/lib/StanfordCPPLib/simpio.cpp new file mode 100755 index 0000000..4f91551 --- /dev/null +++ b/labb5/lib/StanfordCPPLib/simpio.cpp @@ -0,0 +1,67 @@ +/* + * File: simpio.cpp + * ---------------- + * This file implements the simpio.h interface. + */ + +#include +#include +#include +#include +#include "simpio.h" +using namespace std; + +/* + * Implementation notes: getInteger, getReal + * ----------------------------------------- + * Each of these functions reads a complete input line and then uses the + * library to parse that line into a value of the desired type. + * If that fails, the implementation asks the user for a new value. + */ + +int getInteger(string prompt) { + int value; + string line; + while (true) { + cout << prompt; + getline(cin, line); + istringstream stream(line); + stream >> value >> ws; + if (!stream.fail() && stream.eof()) break; + cout << "Illegal integer format. Try again." << endl; + if (prompt == "") prompt = "Enter an integer: "; + } + return value; +} + +double getReal(string prompt) { + double value; + string line; + while (true) { + cout << prompt; + getline(cin, line); + istringstream stream(line); + stream >> value >> ws; + if (!stream.fail() && stream.eof()) break; + cout << "Illegal numeric format. Try again." << endl; + if (prompt == "") prompt = "Enter a number: "; + } + return value; +} + +/* + * Implementation notes: getLine + * ----------------------------- + * The getLine function simply combines the process of displaying a + * prompt and reading an input line into a single call. The primary + * reason for including this function in the library is to ensure + * that the process of reading integers, floating-point numbers, and + * strings remains as consistent as possible. + */ + +string getLine(string prompt) { + string line; + cout << prompt; + getline(cin, line); + return line; +} -- cgit v1.2.1