我正在考虑一种如何遍历用户给定的字符串的方法。它与掷骰子有关;格式:xdy [z],其中x是滚动时间,dy是骰子类型,z只是整数
格式是这样的:从1-999(x)开始的数字,然后是字母d,然后是特定的数字[骰子类型](只能选择5; 4、6、12、20、100),然后带有方括号从1到100的数字...所以一些示例如下所示... 1d4 [57],889d20 [42],43d4 [4],1d4 [1]-999d100 [100]是字符范围,因此6个字符对12个字符。我不确定该怎么做,这就是我现在所拥有的,但是似乎可以有更好的方法来解决这个问题。我从用户那里得到的输入已经使用正则表达式进行了验证,以确保格式正确。我想将值存储在向量数组中,然后将所有内容连接在一起。
void rollDie(std::string input)
{
int bracketCount;
std::vector<int> timesRolled;
std::vector<int> diceType;
std::vector<int> additional;
bool d = false;
bool bc = false;
for (int i = 0; i < input.length; i++) //or length - 1
{
if (isdigit(input[i]))
{
if (bool d = false)
{
timesRolled.push_back(input[i]);
}
}
if(isalpha(input[i]))
{
d = true;
}
if (isdigit(input[i]))
{
if (d = true)
{
diceType.push_back(input[i]);
}
}
if (!isalpha(input[i]) && !isdigit(input[i]))
{
bracketCount++;
bc = true;
if (bracketCount = 2) break;
}
if (isdigit(input[i]))
{
if (bc = true)
{
additional.push_back(input[i]);
}
}
}
}
如果使用正则表达式来验证输入,则最好使用相同的正则表达式来提取值。
就像是:
std::regex e{ R"-((\d{1,3})[Dd](4|6|12|20|100)\[(\d{1,3})\])-" };
std::cout << "Enter dice roll: " << std::flush;
std::smatch m;
for(std::string line; std::getline(std::cin, line);)
{
if(std::regex_match(line, m, e))
break; // if it's good we're done here
// keep going until we get it right
std::cout << "Error: bad format, please use: nnndxx[ddd]" << '\n';
}
int rolls = std::stoi(m[1]);
int sides = std::stoi(m[2]);
int extra = std::stoi(m[3]);
std::cout << "Rolls: " << rolls << '\n';
std::cout << "Sides: D" << sides << '\n';
std::cout << "Extra: " << extra << '\n';
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句