【发布时间】:2022-01-21 21:07:43
【问题描述】:
我想接收来自用户的输入并在文件中搜索该输入。当我找到包含该特定单词的行时,我想打印它并获取另一个输入以根据第二个用户输入和第三个用户输入更改该行的一部分。 (我正在编写一个医院管理应用程序,这是患者和编辑他们的文档的项目的一部分)。 我完成了 90% 的项目,但我不知道如何替换它。查看以下代码:
#include <iostream>
#include <stream>
#include <string.h>
#include <string>
using namespace std;
int main(){
string srch;
string line;
fstream Myfile;
string word, replacement, name;
int counter;
Myfile.open("Patientlist.txt", ios::in|ios::out);
cout << "\nEnter your Name: ";
cin.ignore();
getline(cin, srch);
if(Myfile.is_open())
{
while(getline(Myfile, line)){
if (line.find(srch) != string::npos){
cout << "\nYour details are: \n" << line << endl << "What do you want to change? *type it's word and then type the replacement!*" << endl;
cin >> word >> replacement;
}
// i want to change in here
}
}else
{
cout << "\nSearch Failed... Patient not found!" << endl;
}
Myfile.close();
}
例如我的文件包含这一行 (David , ha , 2002 ) 并且用户想要将 2002 更改为 2003
【问题讨论】:
-
不能直接替换文件中的字符串。您必须在第二个文件中写入您读取的内容,然后重命名/删除原始文件,然后将输出文件重命名为原始名称。
-
@zdf 你能用代码告诉我我该怎么做吗?我没有太多使用 C++ 的经验,非常感谢