Mam problem z moim programem C++ ... Cały mój program to baza danych dla nazwisk studentów, ocen i wieku i mam problem z funkcją, gdy użytkownik chce usunąć dane dla 1 student. Oto kod:C++ usuwanie linii tekstu w pliku
void deletestudentdata()
{
string name, grade, tname;
int age, x=0; // x - "counter" to check if user entered wrong name
system("cls");
cout << "Enter name of the student you want to erase from database" << endl;
cin >> tname;
ifstream students("students.txt");
ofstream temp("temp.txt"); // temp file for input of every student except the one user wants to delete
while(students >> name >> grade >> age)
{
if(tname!=name){ // if there are students with different name, input their data into temp file
temp << name << ' ' << grade << ' ' << age << endl;
}
if(tname==name){ // if user entered correct name, x=1 for later output message that the user data has been deleted
x=1;
}
}
students.clear(); // clear eof and fail bits
students.seekg(0, ios::beg);
students.close();
temp.close();
remove("students.txt");
rename("temp.txt","students.txt");
if(x==0){ // x was set to 0 at start, so if it didn't change, it means user entered the wrong name
cout << "There is no student with name you entered." << endl;
}
else{ // x is not 0, it means user entered the correct name, print message that students data has been deleted
cout << "Student data has been deleted." << endl;
}
}
To działa, ale problemem jest to, że wprowadzanie danych uczniów i gdy chcę usunąć go za pomocą tej funkcji nie usuwa go, najpierw trzeba zamknąć program, a następnie ponownie otwórz program, a następnie wywołaj tę funkcję, aby usunąć dane uczniów.
Jak mogę to zmienić, aby móc usuwać dane uczniów zaraz po wprowadzeniu, bez konieczności uprzedniego zamykania programu?
Czy możesz być bardziej precyzyjny ze sposobem, w jaki go wykonujesz, na przykład: '" Wprowadzam dane ucznia "', jak? – Synxis
Uruchomiłem go w VS2012. Nie widzę żadnego problemu. – shivakumar
Przypuszczalnie przechowujesz listę nazwisk uczniów gdzie indziej podczas uruchamiania twojego programu, nie tylko w pliku, i musisz usunąć tam również ucznia. (Lub wyczyść listę i wypełnij ją ponownie podczas kopiowania nazwisk). –