w pliku "Students.txt znajdują się np dane
Adam Pierwszy Człowiek 0
Ewa Kobieta 2
do vector'a którego typem jest struktura nie wczytuje się ostatnia linijka, lub jest nadpisywana
nie wiem też, czy dobrze ustawiłem flagi
std::ifstream infile("Students.txt", ios::out);
std::ofstream outfile("Tmp_Students.txt", ios::trunc);
poniżej listing
#include <iostream>
#include <iomanip>
#include <limits> // std::numeric_limits
#include <cstring> // strlen
#include <fstream>
#include <string>
#include <vector>
using namespace std;
struct Student
{
std::string firstName;
std::string lastName;
int luckyNumber;
};
std::istream& operator>>(std::istream& is, Student& s)
{
return is >> s.firstName >> s.lastName >> s.luckyNumber;
}
std::ostream& operator<<(std::ostream& os, Student& s )
{
os << s.firstName << " " << s.lastName << " " << s.luckyNumber << "\n";
return os;
}
int main()
{
std::vector<Student> students;
Student new_students;
int how_much, luckyNumber;
string firstName, lastName;
std::ifstream infile("Students.txt", ios::out);
std::ofstream outfile("Tmp_Students.txt", ios::trunc);
infile.seekg(0, ios::beg);
while (infile >> new_students) //|| !infile.eof()
{
students.push_back(new_students);
}
cout << "\tStudents " << students.size() << endl;
for(auto el: students)
{
cout << el.firstName << " " << el.lastName << " " << el.luckyNumber << endl;
}
cout << "\nHow many students you want to add : ";
cin >> how_much;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
for(int i = 0; i < how_much; ++i)
{
cout << "Data for " << i+1 << " student \n";
cout << "your name : ";
//cin >> firstName;
getline(cin, firstName); //o.k.
cout << "your last name : ";
//cin >> lastName;
getline(cin, lastName); //o.k.
cout << "Enter the lucky number : ";
cin >> luckyNumber;
cout << "\nyour data : " << firstName << " " << lastName << " " << luckyNumber << "\n\n";
new_students = { firstName, lastName, luckyNumber };
students.push_back( new_students );
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
cout << "\n\noutfile " << endl;
outfile.seekp(0, ios::beg);
for(auto el: students)
{
cout << el ;
new_students = el;
(outfile << new_students );
}
cout << "\n";
infile.close();
outfile.close();
remove("Students.txt");
rename("Tmp_Students.txt","Students.txt");
return 0;
}