#include <iostream>
#include <string>
#include <fstream>
using namespace std;
//code to register, display and delete a constituency for election using file handling
fstream constituencies("constituencies.txt", ios::out | ios::in);
fstream temp("temp.txt", ios::out | ios::in);
/* declaring files for constituencies registration and when to delete, a temp file to copy the previous data into it and later rename it as constituencies*/
void registerConstituency() // function to register constituency
{
// Proccess for constituency
string consti;
cout << "\n\nEnter unique constituency\n";
getline(cin, consti);
string get_file;
static bool flag = false;
/* flag to detect whether the constituency to be registered is already registered or not */
// searching file if entry by user already exists or not through while loop
while (getline(constituencies, get_file)) {
if (get_file == consti) {
flag = true;
break;
}
}
if (flag == true) {
cout << "\nConstituency already exists, try another one\n";
}
else {
ofstream constituencies("constituencies.txt", ios::app);
constituencies << consti << endl;
cout << "Your Constituency has been registered\n";
constituencies.close();
}
}
void displayConstituency()
{
string get_file;
while (getline(constituencies, get_file))
cout << get_file << endl;
}
void updateOrDelete()
{
string deleteline;
string line;
ofstream temp("temp.txt", ios::app);
cout << "Which constituency do you want to remove? \n";
cin >> deleteline;
while (getline(constituencies, line)) {
if (line != deleteline) {
temp << line << endl;
}
}
remove("constituencies.txt");
rename("temp.txt", "constituencies.txt");
}
void menu()
{
cout << "Select an option:" << endl
<< endl;
cout << "1) Register a national assembly constituency (e.g. NA-1)\n";
cout << "2) List all constituencies\n";
cout << "3) Update/Delete Constituencies \n";
int option;
cout << "option: ";
cin >> option;
switch (option) {
case 1:
registerConstituency();
break;
case 2:
displayConstituency();
break;
case 3:
updateOrDelete();
break;
default: // Invalid option
cout << "INVALID OPTION!!" << endl;
break;
}
}
int main()
{
for (;;) {
menu();
int exit;
cout << "\nENTER ANY NUMBER TO EXIT\n";
cin >> exit;
system("CLS");
}
}
首先,你需要添加 fflush(stdin)
之前 getline(cin, consti)
在第一个定义的函数中,因为它是跳过要求输入的。
现在,我们来解决主要问题。
问题是,第二次执行时,文件内容没有任何显示。
原因是。 即使不读,它也会转到文件的结尾处 while(getline())
语句。
要解决这个问题,请跳到第二个函数 void displayConstituency()
:
void displayConstituency()
{
string file = "";
while (getline(constituencies, file))
cout << file << endl;
// goes end of file and never jumps to beginning for next execution
}
与其这样,不如这样做。
void displayConstituency()
{
string file = "";
constituencies.clear(); // this
constituencies.seekg(0, ios::beg); // this
while (getline(constituencies, file))
cout << file << endl;
}
它清除EOF,第二行再找文件的开头,供将来使用。