[英]C++ Finding a line from a text file and updating/writing the line
我有一个程序应该能够读取的银行帐户文件。 此功能现在使用ifstream工作。 但我希望程序读取文本文件的第6行(其值为'balance'),然后根据需要更新它(删除并替换为新值)。
我使用for循环来查找遍历的遍历。 但是如何在需要时更新它 ? (提款和存款更新余额)
这是我现在的代码:
ifstream file;
string line;
file.open ("accounts.txt", ios::in);
for(int i = 0; i < 6; ++i) //6 being the 6th line
{
getline(file, line);
}
接下来的人会怎么样? 谢谢 :)
如果您的文件非常小,就像您提到的那样,您可以将它带入一个字符串数组(每行文本一个元素)。 然后更改数组并将整个数组重新写回文件。
例如,你可以把它读成这样的arrya:
//assuming you've defined the array A
for(int i = 0; i < 6; i++) //NOTE: I've changed the loop counter i
{
getline(file, line);
A[i] = line;
cout << A[i] < "\n"; //This is the NEW LINE I wanted you to put
//If the ABOVE line gives nothing, you ought to check your TXT file.
}
//Change line 6
A[5] = "555.00";
//Now reopen the file to write
ofstream Account ("accounts.txt");
if (Account.is_open())
{
for(i=0;i<6;i++)
{//NOTE THAT I HAVE INCLUDED BRACES HERE in case you're missing something.
Account << A[i] << "\n"; //Loop through the array and write to file
}
Account.close();
}
我没有测试这个,但我认为没关系。 更多代码:如果在主代码末尾添加以下代码,则应该看到数组中的内容。 如果这没有显示任何明显意味着您的文件是空的。
for(int i = 0; i < 6; i++)
{
cout << A[i] < " This is a row with data\n";
}
注意:虽然我想帮助您解决本论坛上的澄清问题,但我认为这个问题超出了本论坛的性质。 也许你需要的是花一些时间学习循环和其他结构的艺术:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.