diff options
| author | Gustav Sörnäs <gustav@sornas.net> | 2020-12-01 15:25:23 +0100 |
|---|---|---|
| committer | Gustav Sörnäs <gustav@sornas.net> | 2020-12-01 15:25:23 +0100 |
| commit | 93c6b29368d1e0487937b433bc6e678da0058055 (patch) | |
| tree | 5e749adfecf2eab82b5e78bbeacc52fc8e2298fb /labb6/lib/StanfordCPPLib/simpio.cpp | |
| parent | d4f35cf45ebc655d92cde8abb5c9a1c2822a08ba (diff) | |
| download | tddd86-93c6b29368d1e0487937b433bc6e678da0058055.tar.gz | |
given code l6
Diffstat (limited to 'labb6/lib/StanfordCPPLib/simpio.cpp')
| -rwxr-xr-x | labb6/lib/StanfordCPPLib/simpio.cpp | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/labb6/lib/StanfordCPPLib/simpio.cpp b/labb6/lib/StanfordCPPLib/simpio.cpp new file mode 100755 index 0000000..4f91551 --- /dev/null +++ b/labb6/lib/StanfordCPPLib/simpio.cpp @@ -0,0 +1,67 @@ +/* + * File: simpio.cpp + * ---------------- + * This file implements the simpio.h interface. + */ + +#include <fstream> +#include <iostream> +#include <sstream> +#include <string> +#include "simpio.h" +using namespace std; + +/* + * Implementation notes: getInteger, getReal + * ----------------------------------------- + * Each of these functions reads a complete input line and then uses the + * <sstream> 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; +} |
