如何在文本文件中逐行搜索

问题描述 投票:1回答:3
123 Michael
456 Calimlim
898 Mykfyy
999 Kyxy
657 mykfyy
898 Help

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

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

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

c++ ifstream ofstream id
3个回答
2
投票

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


1
投票

最简单的方法是使用std :: getline将当前行作为字符串:

using namespace std;
ifstream in(fileName);

string line;
while(getline(in, line))
{
    // --do something with the line--
}

然后,您需要解析每一行以获取正确的ID

编辑:更新以删除eof()


0
投票

取决于你如何实现它。

我想人数不是太大,所以我只想在添加新ID之前检查Id。

如果ID存在,则不添加。

© www.soinside.com 2019 - 2024. All rights reserved.