I have to read console input and store data in the vector of structs. In case of any data format violation I have to print "Malformed Input" and return 1
Data format:
1 The first line is "#job_id,runtime_in_seconds,next_job_id"
2 The next lines are three comma separated integers (number of lines can be different)
Example:
#job_id,runtime_in_seconds,next_job_id
1,60,23
2,23,3
3,12,0
23,30,0
Could you please advise how to write better code in terms of time performance?
I was thinking about scanf("%d,%d,%d", &arg1, &arg2, &arg3) but not sure that it's C++ style
My code:
#include <iostream>
#include <optional>
#include <vector>
using namespace std;
struct Job {
int job_id;
int runtime;
int next_job_id;
};
std::optional<Job> make_job(const string& s) {
int job_id = 0, runtime = 0, next_job_id = 0;
int i = 0;
while (i < s.size() and s[i] >= '0' and s[i] <= '9') {
job_id = job_id * 10 + (s[i] - '0');
++i;
}
if (i == s.size() or s[i] != ',') {
return nullopt;
}
++i;
while (i < s.size() and s[i] >= '0' and s[i] <= '9') {
runtime = runtime * 10 + (s[i] - '0');
++i;
}
if (i == s.size() or s[i] != ',') {
return nullopt;
}
++i;
while (i < s.size() and s[i] >= '0' and s[i] <= '9') {
next_job_id = next_job_id * 10 + (s[i] - '0');
++i;
}
if (i != s.size()) {
return nullopt;
}
return Job {job_id, runtime, next_job_id};
}
int main() {
string line;
getline(cin, line);
if (line.compare("#job_id,runtime_in_seconds,next_job_id")) {
cout << "Malformed Input";
return 1;
}
vector<Job> jobs;
while (getline(cin, line)) {
const auto job = make_job(line);
if (not job) {
cout << "Malformed Input";
return 1;
}
jobs.push_back(*job);
}
// process Jobs
return 0;
}