c++ - 迭代 std::string C++

标签 c++ regex loops parsing string-parsing

我正在考虑一种如何遍历用户给定的字符串的方法。它与掷骰子有关;格式: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 个字符 vs 12 个字符。我不确定该怎么做,这就是我现在所拥有的,但似乎可以有更好的方法来解决这个问题。我从用户那里得到的输入已经使用正则表达式进行了验证,以确保格式正确。我想将值存储在 vector 数组中,然后最后连接所有内容。

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';

关于c++ - 迭代 std::string C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40100001/

相关文章:

c - 扩展正则表达式是否支持反向引用?

逐行运行文件的python -regex匹配和for循环

python - 更快/更智能的循环 [Python]

Java蛇眼程序错误

c++ - 如何在 ubuntu 上使用可移植 Clang 设置 CLion?

c++ - 在 OpenCV Mat 和 Leptonica Pix 之间转换

c++ - 原生类型的封装会影响效率吗?

javascript - 将枚举(作为字符串)从 CAPS_CASE 转换为驼峰式

regex - 匹配某物而不匹配某物的正则表达式

c++ - LLDB是如何实现设置断点功能的?