Есть программа. Она создаёт текстовый файл input.txt, который содержит информацию о студентах (ФИО, Группа, Номер зачётки, Факультет) Нужно отсортировать эту информацию, а именно, по возрастанию номеров групп и ФИО, и записать в новый файл output.txt. Заранее спасибо всем ответившим.
#include <fstream>
#include<iostream>
using namespace std;
int main()
{
setlocale(LC_ALL, "RUS");
string path = "input.txt";
ofstream fout;
http://fout.open/ (path);
if (! http://fout.is/ _open())
{
cout << "Ошибка открытия файла! " << endl;
}
else
{
fout << "Иванов Иван Иванович, 19КТ5, 5, математический" << "\n"; //ФИО, Группа, Номер зачётки, Факультет
fout << "Смирнов Алексей Николаевич, 20КС4, 2, исторический" << "\n";
fout << "Кузнецов Дмитрий Анатольевич, 21МН1, 4, экономический" << "\n";
}
fout.close();
string patsh = "output.txt";
ifstream fin;
if (! http://fin.is/ _open())
{
cout << "Ошибка открытия файла! " << endl;
}
else
{
cout << "Файл открыт! " << endl;
char ch;
while (fin.get(ch))
{
cout << ch;
}
}
fin.close();
return 0;
}
C/C++
Input.txt и output.txt. Работа с текстовыми файлами C++.
#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
using namespace std;
struct Student {
unsigned id;
string name;
string group;
string faculty;
private:
friend bool operator<(const Student& a, const Student& b) {
if (a.group < b.group) return true;
if (a.group == b.group && a.name < b.name) return true;
return false;
}
};
vector<Student> database() {
return vector<Student> {
{ 1, "Иванов Иван Иванович", "19ИС8", "исторический" },
{ 2, "Смирнов Алексей Николаевич", "20ФЛ4", "филологический" },
{ 3, "Кузнецов Дмитрий Анатольевич", "21БЛ9", "биологический" },
{ 4, "Фёдорова Анна Васильевна", "19ИС8", "исторический" },
{ 5, "Говоров Захар Борисович", "21БЛ9", "биологический" },
{ 6, "Антонова Светлана Петровна", "19ИС8", "исторический" },
{ 7, "Тимофеева Тамара Васильевна", "20ФЛ4", "филологический" }
};
}
void create(const string path) {
ofstream out(path);
if (out.is_open()) {
auto db = database();
for (const auto& rec : db) {
out
<< rec.name << '\n'
<< rec.group << '\n'
<< rec.id << '\n'
<< rec.faculty << '\n';
}
out.close();
}
}
int main() {
system("chcp 1251 > nul");
const string input{ "input.txt" };
ifstream inp(input);
if (!inp.is_open()) create(input);
if (inp.is_open()) {
inp.seekg(0, ios::end);
if (!inp.tellg()) create(input);
inp.close();
}
ifstream file(input);
if (file.is_open()) {
const string output{ "output.txt" };
vector<Student> students;
Student student;
while (!file.eof()) {
getline(file, student.name);
getline(file, student.group);
file >> student.id;
file.ignore(numeric_limits<streamsize>::max(), '\n');
getline(file, student.faculty);
students.emplace_back(student);
}
file.close();
sort(students.begin(), students.end());
ofstream out(output);
if (out.is_open()) {
for (const auto& rec : students) {
if (!rec.name.empty()) {
out << rec.group << ' '
<< rec.name << ", "
<< rec.faculty << ", "
<< rec.id << '\n';
}
}
} else {
puts("Что-то пошло не так при записи в файл...");
system("pause > nul");
}
} else {
puts("Что-то пошло не так при чтении из файла...");
system("pause > nul");
}
}
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
using namespace std;
struct Student {
unsigned id;
string name;
string group;
string faculty;
private:
friend bool operator<(const Student& a, const Student& b) {
if (a.group < b.group) return true;
if (a.group == b.group && a.name < b.name) return true;
return false;
}
};
vector<Student> database() {
return vector<Student> {
{ 1, "Иванов Иван Иванович", "19ИС8", "исторический" },
{ 2, "Смирнов Алексей Николаевич", "20ФЛ4", "филологический" },
{ 3, "Кузнецов Дмитрий Анатольевич", "21БЛ9", "биологический" },
{ 4, "Фёдорова Анна Васильевна", "19ИС8", "исторический" },
{ 5, "Говоров Захар Борисович", "21БЛ9", "биологический" },
{ 6, "Антонова Светлана Петровна", "19ИС8", "исторический" },
{ 7, "Тимофеева Тамара Васильевна", "20ФЛ4", "филологический" }
};
}
void create(const string path) {
ofstream out(path);
if (out.is_open()) {
auto db = database();
for (const auto& rec : db) {
out
<< rec.name << '\n'
<< rec.group << '\n'
<< rec.id << '\n'
<< rec.faculty << '\n';
}
out.close();
}
}
int main() {
system("chcp 1251 > nul");
const string input{ "input.txt" };
ifstream inp(input);
if (!inp.is_open()) create(input);
if (inp.is_open()) {
inp.seekg(0, ios::end);
if (!inp.tellg()) create(input);
inp.close();
}
ifstream file(input);
if (file.is_open()) {
const string output{ "output.txt" };
vector<Student> students;
Student student;
while (!file.eof()) {
getline(file, student.name);
getline(file, student.group);
file >> student.id;
file.ignore(numeric_limits<streamsize>::max(), '\n');
getline(file, student.faculty);
students.emplace_back(student);
}
file.close();
sort(students.begin(), students.end());
ofstream out(output);
if (out.is_open()) {
for (const auto& rec : students) {
if (!rec.name.empty()) {
out << rec.group << ' '
<< rec.name << ", "
<< rec.faculty << ", "
<< rec.id << '\n';
}
}
} else {
puts("Что-то пошло не так при записи в файл...");
system("pause > nul");
}
} else {
puts("Что-то пошло не так при чтении из файла...");
system("pause > nul");
}
}
ツ
Похожие вопросы
- Работа с текстовым файлом. С++
- Помогите решить задачку по теме работа с файлами C++
- Помогите с файлами C++
- Помогите написать код с файлами C++
- Как записать данные в бинарный файл C++
- Помогите написать код с файлами C++
- Объясните работу цикла for в c++
- Работа с классами в C++
- Cоставление и отладка программ работы с двумерными массивами C++
- Cоставление и отладка программ работы с двумерными массивами. C++