First, construct a struct
(or class
if you so prefer) to bind your data i.e. the rolls required and the possible faces into one data structure, something like:
struct Die {
int rolls;
int faces;
};
In C++, if you need a dynamic array, prefer to use a std::vector
since a lot of the internal memory management (like new
/delete
) is abstracted away. So, what we need is an array of Die
s i.e std::vector<Die>
. Now what remains is just reading in the data. First, some error handling
std::ifstream inp("test.txt");
//if error opening file display Error
if(!inp){
std::cout << "Error opening file";
return 1;
}
That gets rid of file-opening errors. Next, we create an empty array of Die
elements.
std::vector<Die> arr;
Now, it's simple to read in the elements of the Die
, one by one:
Die die;
while(inp>>std::ws>>die.rolls) {
inp.ignore(std::numeric_limits<std::streamsize>::max(), '-');
inp>>std::ws>>die.faces;
arr.push_back(die);
}
The std::ws
is just to ignore all whitespaces from the input file line. The inp.ignore()
part basically reads and ignores all the characters up to -
as specified in the code and then the die.faces
is read after having ignored the -
character. That's it, that reads in one line of numbers like 2-6
. Now that just needs to be repeated till the file has no more data to be read, which is taken care of by the while
condition while(inp>>std::ws>>die.rolls)
.