0
我正在研究一个大学项目,它需要我在文本文件中找到一个值,并将其替换为一个新值,我已将其存储在一个浮点变量中,问题的一部分是我不知道该项目需要被替换的地方,只有它的位置(例如我可以搜索0.00的值,但多个记录可以有这个平衡)。如何在文本文件中找到一行并将其替换?
的文本文件布局像这样:
USERNAME1
密码1
AccountNo1
余额1
Jimmy54
FooBar123
13.37
...
而且我的代码的相关部分看起来是这样的:
用户输入自己的用户名,我们就
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
cout << "Please enter your username:\n";
cin >> enteredName;
关于100线下存储在enteredName中,我们得到的一部分,这个重要的代码问题:
if (c2 == 1)
{
//irrelevant to problem
}
else if (c2 == 2)
{
float convBal;
float deposit;
string newBal;
convBal = ::atof(ball.c_str());
/* Ball is declared higher up in the code and just contains a
value pulled from the text file for the sake of the question
we'll say it has a value of 0.00 */
cout << "How much would you like to deposit?:\n";
cin >> deposit;
newBal= convBal + deposit;
cout << "Your total balance is now: "<< newBal << "\n\n";
}
}
所以需要从这里做的事情是打开文件,搜索enteredName文件(在这种情况下,我们会说Jimmy54),然后更换用户名下方值3线(13.37)与价值存储在newBal
在此先感谢!很抱歉,如果这听起来像一个愚蠢的问题,我很新的节目,甚至较新的C++的
编辑#1: 这里是我到目前为止的代码,发现enteredName然后得到3线如下:
if (myfile.is_open())
{
while (getline(myfile, line))
{
if (line.compare(enteredName) == 0)
{
getline(myfile, line); //Password
getline(myfile, line); //Account Number
getline(myfile, line); //Balance
}
}
}
myfile.close();
如果您遇到困难,请尝试编写一些内容并提出具体问题。 – stark
@stark我已经编辑了我的帖子,目前为止我的进度已经找到,但我找不到如何更改它 –
编写文件不像在编辑器中操作它,所以你不能“替换”一行,因为如果增加/缩短行的长度,文件的其余部分将不会移动。你*可以*覆盖固定大小的数据,但最简单的方法来做你想做的事情就是打开一个新的输出文件并复制行。 – kfsone