1

I want to find a specific id from file and modify content.
Here is originol code which I want.

// test.txt id_1 arfan haider id_2 saleem haider id_3 someone otherone 

C++ Code:

#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; } } } 

Suppose:
A user search id *id_2*. After that user enter First name and Last name Shafiq and Ahmed.
After runing this code the test.txt File must modify the record like that:

............... ............... id_2 Shafiq Ahmad ................. ................. 

Only id_2 record change remaing file will be same.
UPDATE:

#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; } } } 

It also contain pervious First Name and Last Name in temp.txt file.

0

1 Answer 1

1

After finding the specific id and writing the new first name and last name, you need to skip the following two lines. This code works:

#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; } } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.