In C++ one wouldn't deal with lines, but with objects:
#include <limits>
#include <cstdlib>
#include <vector>
#include <string>
#include <fstream>
#include <iostream>
#include <iterator>
#include <algorithm>
struct student_t
{
unsigned id;
std::string name;
};
bool operator==(student_t const &lhs, student_t const &rhs)
{
return lhs.id == rhs.id;
}
std::ostream& operator<<(std::ostream &os, student_t const &student)
{
return os << student.id << ' ' << student.name;
}
std::istream& operator>>(std::istream &is, student_t &student)
{
unsigned id;
if (!(is >> id))
return is;
std::string name;
if (!std::getline(is, name)) {
return is;
}
student = student_t{ id, name };
return is;
}
int main()
{
char const *filename{ "test.txt" };
std::ifstream input{ filename };
if (!input.is_open()) {
std::cerr << "Couldn't open \"" << filename << "\" for reading :(\n\n";
return EXIT_FAILURE;
}
std::vector<student_t> students{ std::istream_iterator<student_t>{ input }, std::istream_iterator<student_t>{} };
input.close();
std::copy(students.begin(), students.end(), std::ostream_iterator<student_t>{ std::cout, "\n" });
student_t new_student;
while (std::cout << "New Student?\n", !(std::cin >> new_student)) {
std::cerr << "Input error :(\n\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
auto it{ std::find(students.begin(), students.end(), new_student) };
if (it != students.end()) {
std::cerr << "Sorry, but a student with id " << new_student.id << " already exists :(\n\n";
return EXIT_FAILURE;
}
std::ofstream output{ filename, std::ios::app };
if (!output.is_open()) {
std::cerr << "Couldn't open \"" << filename << "\" for writing :(\n\n";
return EXIT_FAILURE;
}
output << new_student << '\n';
std::cout << "New student [" << new_student << "] added :)\n\n";
}