epr24pr5-ojanssen2/Util.cpp

75 lines
1.7 KiB
C++
Raw Permalink Normal View History

#include "Util.h"
#include "Error.h"
#include <exception>
#include <string>
using err::Error;
namespace util {
string Util::read_string_between_percent(istream& is) {
char c;
string s = "";
bool read = false;
for(int i = 0; i < 2; ++i) {
while (true) {
is >> c;
if (!is)
throw Error(700, "Could not read char!");
if (c == '%') {
read = !read;
break;
}
if (!read)
continue;
s += c;
}
}
return s;
}
vector<int> Util::read_numbers(istream &is) {
string until_eol;
getline(is, until_eol);
vector<string> numbers_as_string = split(until_eol);
vector<int> nums;
try {
for(string s : numbers_as_string)
nums.push_back(stoi(s));
} catch (exception& _) {
throw Error(700, "Could not convert string to int.");
}
return nums;
}
vector<string> Util::split(const string& s) {
vector<string> strs;
string result = "";
for(char c : s) {
if (c == ' ') {
if (result != "") {
strs.push_back(result);
result = "";
}
break;
}
result += c;
}
return strs;
}
string Util::read_string(istream &s) {
string result;
s >> result;
if (!s)
throw Error(700, "Could not read stream from stream!");
return result;
}
} // util