c++ - 货币面额

标签 c++ string parsing

尝试为我的游戏使用正确的货币面额。货币存储为字符串(即由于我的教授而无法更改)并且按白金、黄金、白银和铜的顺序排列。例如,如果我将我的货币初始化为“0.1.23.15”,这意味着我有 0 个白金、1 个金、23 个银和 15 个铜。

但是,我需要能够转换为更高的面额。这意味着什么?举个例子,如果我有 105 个银币(即 0.0.105.0),它应该显示为 1 个金币和 5 个银币(即 0.1.5.0)。

我在 setCost 方法中用粗体显示了我的问题。我正在检查一个数字是否大于 100,如果是——我将该列设置为 0,返回到前一个元素并将 1 添加到 ASCII 值以提供适当的进位。不幸的是,调试器显示“/x4”被转储到元素中,而不仅仅是“4”。有谁知道这是为什么以及我该如何改变它??

编辑:编辑了代码,只要您输入的数字不超过 100,它就可以正常工作。对于如何使其适用于大于 100 的数字,我的大脑失误了。

这是我写过的最草率的代码。请温柔点:(

void Potion::setCost(std::string cost)
{
    char buffer[256];
    std::string currencyBuffer [4];
    int integerBuffer[4];
    int * integerPointer = nullptr;
    int temp = 0;
    int i = 0;
    char * tokenPtr;
    //Convert string to cString
    strcpy(buffer, cost.c_str() );

    //Tokenize cString
    tokenPtr = strtok(buffer, ".");

    while(tokenPtr != nullptr)
    {
        //Convert ASCII to integer
        temp = atoi(tokenPtr);

        //Store temp into currency buffer
        integerBuffer[i] = temp;

        //Make pointer point to integer buffer
        integerPointer = &integerBuffer[i];

        if(*integerPointer < 100)
            currencyBuffer[i] = tokenPtr;
        else
        {
            //Store zero in column if number is 
            //greater than 100
            temp2 = temp % 100;
            itoa(temp2, temp3, 10);
            currencyBuffer[i] = temp3;

            //Go back and add one to currency buffer
            temp = atoi(currencyBuffer[i-1].c_str());
            temp += 1;
            itoa(temp, temp3, 10);
            currencyBuffer[i - 1] = temp3;
        }

        i++;

        //Get next token
        tokenPtr = strtok(nullptr, ".");
    }
    NewLine();

    std::string tempBuffer;

    //Store entire worth of potions
    tempBuffer = "Platinum: ";
    tempBuffer += currencyBuffer[0];
    tempBuffer += "\nGold: ";
    tempBuffer += currencyBuffer[1];
    tempBuffer += "\nSilver: ";
    tempBuffer += currencyBuffer[2];
    tempBuffer += "\nCopper: ";
    tempBuffer += currencyBuffer[3];

    mCost = tempBuffer;
}

最佳答案

我认为问题出在这一行:

currencyBuffer[i - 1] = temp;

您将一个 int (temp) 分配给一个字符串 (currencyBuffer[i-1]),这会导致写入垃圾字符。显然,这是允许的: ( Why does C++ allow an integer to be assigned to a string? ) 因为 int 可以隐式转换为 char,而 char 可以分配给字符串。

您想使用 itoa 或类似函数将 temp 转换为 char(当您从字符串中获取 int 时,您已经正确执行了相反的操作,atoi)。

由于您使用的是 C++,因此执行此操作的简单方法是:

std::stringstream itos;
itos << temp;
currencyBuffer[i-1] = itos.c_str();

关于c++ - 货币面额,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15825222/

相关文章:

java - 我的 int 数组出了什么问题?

python - 如何在文件读取期间从每一行中去除换行符?

java - 使用java验证json文件

c++ - 将 regex_search 与 std::string 一起使用时的无限循环

C++ boost 线程 ID 和单例

c++ - 如何将 Eigen 库添加到 C++ 项目中

从 java 代码调用 javascript

c++ - 写入文本文件而不覆盖它

c - 为什么我们必须添加 NULL 才能在 C 中使用指针打印保留字符串?

parsing - 如何解析、操作和保存 Adob​​e Photoshop 文件?