how to edit particular data in file








i have this data in my file
1234
Alex
4th
3
1235
Sam
4th
3
1233
Salman
4th
3

i wanted to change the semester of sam what should i do

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
  #include<iostream>
#include<fstream>
#include<string>
using namespace std;

void insert()
{
	ofstream file;
	file.open("file.txt", ios::app);
	string name, semester;
	int id;
	double gpa;

	cout << "\nEnter Student Id : ";
	cin >> id;
	cout << "\nEnter The Student Name : ";
	cin.ignore();
	getline(cin, name);
	cout << "\nEnter The Student Semester : ";
	cin >> semester;
	cout << "\nEnter The Student Gpa : ";
	cin >> gpa;

	file << id << endl;
	file << name << endl;
	file << semester << endl;
	file << gpa << endl;
}

void display()
{
	bool check = true;
	ifstream file;
	file.open("file.txt");

	string name, semester;
	int id, findid;
	double gpa;

	if (file.fail())
	{
		cerr << "File Not Created or File Name is Not Valid";
	}
	else
	{
		cout << "\nEnter The Id : ";
		cin >> findid;
		while (file >> id&&cin.ignore(40), getline(file, name) && file >> semester , file >> gpa)
		{
			if (id == findid)
			{
				cout << name << endl;
				cout << id;
				cout << semester << endl;
				cout << gpa << endl;
				check = false;
			}
		}
		file.clear();
		file.seekg(0, ios::beg);
	}

	if (check == true)
		cout << "\nStudent Not Found";
}

void deletestd()
{
	ofstream tempfile("temp.txt");
	ifstream file("file.txt");
	string name, semester;
	int id, findid;
	double gpa;

	if (file.good())
	{
		cout << "\nEnter The Student You Want To Delete : ";
		cin >> findid;
		while (file >> id&&cin.ignore(40, '\n'), getline(file, name) && file >> semester, file >> gpa)
		{
			if (findid != id)
			{
				tempfile << id << endl;
				tempfile << name << endl;
				tempfile << semester << endl;
				tempfile << gpa << endl;
			}
		}
	}
	else
	{
		cerr << "\nFile not found\n";
	}

	file.close();
	tempfile.close();

	delete("file.txt");
	rename("tempfile.txt", "file.txt");
}

void editstd()
{
	// what should i do
}


int main()
{
	insert();
	insert();
	insert();
	display();
	display();
	deletestd();
	system("pause");
}
you'll find some ideas below but the best way would be to read the input file into structs, change the corresponding data member of the selected struct and then read the structs back into the input file or to another file

http://stackoverflow.com/questions/9505085/replace-a-line-in-text-file
http://stackoverflow.com/questions/21180412/search-and-replace-string-in-txt-file-in-c
Topic archived. No new replies allowed.