In: Computer Science
Please find the requested program below. Also including the screenshot of sample output and screenshot of code to understand the indentation.
Please provide your feedback
Thanks and Happy learning!
#include <iostream>
#include <string>
#include <sstream>
#include <time.h>
int main()
{
std::string strInput;
int diceCount = 1;
int diceSideCount = 6;
std::cout << "Enter the input in the format nDx or ndx : ";
std::getline(std::cin, strInput);
if (!strInput.empty())
{
size_t foundPos = 0;
if ((foundPos = strInput.find_first_of('d')) == std::string::npos && (foundPos = strInput.find_first_of('D')) == std::string::npos)
{
std::cout << "ERROR: Invalid input format." << std::endl;
return 1;
}
std::string strCount = strInput.substr(0, foundPos);
std::string strSideCount = strInput.substr(foundPos + 1);
//If n is absent, x must be present. If x is absent, n must be present.
if (strCount.empty() && strSideCount.empty())
{
std::cout << "ERROR: Invalid input." << std::endl;
return 1;
}
std::stringstream ss;
ss.clear();
if (!strCount.empty())
{
ss << strCount;
ss >> diceCount;
}
ss.clear();
ss.flush();
if (!strSideCount.empty())
{
ss << strSideCount;
ss >> diceSideCount;
}
srand(time(NULL));
int totalDiceReading = 0;
for (int i = 1; i <= diceCount; ++i)
{
//roll the dice;
//Generate a random value between 1 and diceSideCount
int diceReading = std::rand() % diceSideCount + 1;
//show the individual dice if n > 1.
if (diceCount > 1)
{
std::cout << "Dice " << i << " reading: " << diceReading << std::endl;
}
totalDiceReading += diceReading;
}
std::cout << "Total dice reading : " << totalDiceReading << std::endl;
}
else
{
std::cout << "ERROR: Invalid input." << std::endl;
}
return 0;
}