gpt4 book ai didi

c++ - 使用 fstream 读写同一个文件

转载 作者:行者123 更新时间:2023-11-30 01:55:39 25 4
gpt4 key购买 nike

void Withdraw(int index, int amount)
{
int Balindex = 0;
fstream input("Balance.txt");
float balance = 0.0;
while ((!input.eof())&&(Balindex != index))
{
balance = 0.0;
input >> balance;
Balindex++;
}
input >> balance;
balance = balance - amount;
input << balance << endl;
}

我正在尝试从文本文件中读取余额,并扣除提取的金额。索引保存余额的时间顺序。但是我的文件不会用新值覆盖现有值。有什么建议吗?

最佳答案

在没有中间搜索的情况下在文件流的输入和输出之间切换时,您会得到未定义的行为。去哪里寻找并不重要,但你需要去寻找!例如,您可以从当前位置寻求零字符,或者更可能的是,回到值实际开始的位置:

std::streampos start = input.seekg(0, std::ios_base::cur);
if (input >> balance) {
input.seekp(start);
input << (balance - amount);
}

但是请注意,流不会为其他字符腾出空间,即,如果您读取的内容比您写入的内容短,您将覆盖原始输入之后的数据。同样,您只会覆盖您覆盖的字符。我建议不要做那样的事情。如果您想更新文件,请确保您使用的是固定宽度的记录!

当然,您也不应该使用 input.eof() 来验证流是否正常:如果流进入故障模式,例如,由于格式错误的输入,您永远不会达到 input.eof() 产生 true 的地步,也就是说,你会得到一个无限循环。只需使用流本身作为条件。就个人而言,我会使用类似的东西

while (input >> balance && Balindex != index) {
++Balindex;
}

关于c++ - 使用 fstream 读写同一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20545155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com