在C ++中查找和修改文本文件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在C ++中查找和修改文本文件相关的知识,希望对你有一定的参考价值。
我想从文件中找到特定的id
并修改内容。
这是我想要的原始代码。
// test.txt
id_1
arfan
haider
id_2
saleem
haider
id_3
someone
otherone
C ++代码:
#include <iostream>
#include <fstream>
#include <string>
using namesapce std;
int main(){
istream readFile("test.txt");
string readout;
string search;
string Fname;
string Lname;
cout<<"Enter id which you want Modify";
cin>>search;
while(getline(readFile,readout)){
if(readout == search){
/*
id remain same (does not change)
But First name and Last name replace with
user Fname and Lname
*/
cout<<"Enter new First name";
cin>>Fname;
cout<<"Enter Last name";
cin>>Lname;
}
}
}
假设:
用户搜索ID * id_2 *。之后,用户输入名字和姓氏Shafiq和Ahmed。
运行此代码后,test.txt
文件必须修改如下记录:
...............
...............
id_2
Shafiq
Ahmad
.................
.................
只有id_2
记录更改重映射文件将是相同的。
更新:
#include <iostream>
#include <string.h>
#include <fstream>
using namespace std;
int main()
{
ofstream outFile("temp.txt");
ifstream readFile("test.txt");
string readLine;
string search;
string firstName;
string lastName;
cout<<"Enter The Id :: ";
cin>>search;
while(getline(readFile,readLine))
{
if(readLine == search)
{
outFile<<readLine;
outFile<<endl;
cout<<"Enter New First Name :: ";
cin>>firstName;
cout<<"Enter New Last Name :: ";
cin>>lastName;
outFile<<firstName<<endl;
outFile<<lastName<<endl;
}else{
outFile<<readLine<<endl;
}
}
}
它还包含temp.txt
文件中的前一个名字和姓氏。
答案
找到特定的ID并写入新的名字和姓氏后,您需要跳过以下两行。此代码有效:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void skipLines(ifstream& stream, int nLines)
{
string dummyLine;
for(int i = 0; i < nLines; ++i)
getline(stream, dummyLine);
}
int main()
{
ofstream outFile("temp.txt");
ifstream readFile("test.txt");
string readLine;
string search;
string firstName;
string lastName;
cout<<"Enter The Id :: ";
cin>>search;
while(getline(readFile,readLine))
{
if(readLine == search)
{
outFile<<readLine;
outFile<<endl;
cout<<"Enter New First Name :: ";
cin>>firstName;
cout<<"Enter New Last Name :: ";
cin>>lastName;
outFile<<firstName<<endl;
outFile<<lastName<<endl;
skipLines(readFile, 2);
}
else
{
outFile<<readLine<<endl;
}
}
}
以上是关于在C ++中查找和修改文本文件的主要内容,如果未能解决你的问题,请参考以下文章
vc++2010设置和c#一样的代码段,vs2010 两下tab设置