put()不将值添加到fstream中

时间:2014-07-08 06:35:34

标签: c++

我一直在尝试创建一个程序,该程序从用户获取输入,包括十六进制偏移量和值,并将其插入到fstream中。最初这是有效的,但只有一个值(00到ff)。

现在,我试图一次将字符串转换为int 2字符,并使用put()将值放入fstream。它正确地获取偏移量,正确地将字符串转换为整数(从我可以告诉的),但它似乎没有将值放入fstream。

void write_offset(fstream &in, int offset)
{
    string value;
    unsigned int size;
    ostringstream os;
    unsigned int replace_value;
    unsigned int pos;
    string pause;
    bool valid = true;

    in.seekp(offset);
    cout << "Enter Value: ";
    cin_flush();
    cin >>  value;

    for (char& c : value)
    {
        if (!isdigit(c) && !((c <= 'f' && c >= 'a') || (c <= 'F' && c >= 'A')))
        {
            valid = false;
        }
    }

    if (valid)
    {
        size = value.length();

        cout << value << " " << size << endl;
        if (size % 2 != 0)
        {
            size++;
        }

        read_offset(in, offset, ceil(size / 2));

        for (unsigned int i = 0; i < (size / 2); i++)
        {
            stringstream buff(value.substr((i * 2), 2));
            unsigned int buff_val;


            buff >> hex >> buff_val;

            cout << hex << buff_val << " -> " << dec << buff_val << endl;

            in.seekp(offset + i);
            replace_value = read_offset_int(in, offset + i, 1);
            pos = in.tellg();

            cout << "Replacing " << replace_value << " with " <<  buff_val << " (offset " << (pos - 1) << ")" << endl << endl;

            in.put(buff_val);
        }

        cout << "Enter 'save' to save the hex edits you have done, or write if you wish to do another." << endl;
    }

    else
    {
        cout << "There was a problem with your hex value! (" << value << ")" << endl;
    }
}

输出看起来像这样:

Enter Offset: 3b
Enter Value: fe384ecd
fe384ecd 8
Value at offset (3b) (length 4): 00 48 01 00
fe -> 254
Value at offset (3b) (length 1): 00
Replacing 0 with fe (offset 3b)
38 -> 56
Value at offset (3c) (length 1): 48
Replacing 48 with 38 (offset 3c)
4e -> 78
Value at offset (3d) (length 1): 01
Replacing 1 with 4e (offset 3d)
cd -> 205
Value at offset (3e) (length 1): 00
Replacing 0 with cd (offset 3e)

但是,即使在使用close()之后,也没有任何变化。

如果需要提供任何其他代码,我会这样做,但我很确定问题出在这个循环的某个地方。

编辑:好的,我试过而不是将输入作为字符串读取,将其读作整数(最初工作)。它似乎工作正常,但使用字符串的原因是我希望能够输入多个值。我已经将代码更改为整个函数。

0 个答案:

没有答案