gpt4 book ai didi

c++ - 如何在文本文件中逐行搜索

转载 作者:行者123 更新时间:2023-11-30 02:15:41 25 4
gpt4 key购买 nike

123 Michael
456 Calimlim
898 Mykfyy
999 Kyxy
657 mykfyy
898 Help

我正在创建一个学生出勤系统。我的系统的特点之一是学生需要先注册(他/她的 ID 和姓名)才能访问系统(使用他/她的 ID 登录)

问题是我不知道而且我不希望我的学生有类似的 ID 号码(例如 898 Mykfyy 和 898 Help)

我在我的系统中使用 fstream。我一直在想,如果我想避免重复,我需要在注册(outstream)之前读取(ifstream).txt 文件。但我不知道如何逐行阅读并检查 ID(898) 是否已被使用/存在

最佳答案

在 C++ 中,人们不会处理线,而是处理对象:

#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";
}

关于c++ - 如何在文本文件中逐行搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55852499/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com