c++ - 如何检查从键盘输入的特定整数值是否存在于 C++ 文件的一行或多行中

标签 c++ string operator-overloading fstream

我有一个 C++ 类(class)的小项目,我一直在尝试检查文件中是否存在 STUDENT 类的数据成员的值(“ID”)。我尝试使用我在 Internet 上找到的一些函数将我正在搜索的整数值转换为字符串,然后使用 find 函数在文件的每一行中搜索它。

它有效,但每当我检查文件中的一行时,它都会得到错误的正向,因为 ID 值(例如“12”)与年龄值(也为“12”)相同。这样做是因为年龄值在我的文件和字符串变量中出现在 ID 值之前(我无法更改它)。我不知道只在字符串中搜索 ID 的值。我使用函数“inputInfo”从键盘输入student1 的成员值,并使用函数“checkID”检查文件中是否已经存在“ID”的值。此外,对于项目的另一方面,我正在寻找一种方法来搜索同一文件中 ID 和名称数据成员值的出现(一旦它们已经写入)。我想过的一种解决方案是以某种方式在另一个字符出现后开始搜索(例如空格字符,因为在文件中,每个字段都用空格与另一个字段分隔),但我不确定查找函数能够做到这一点。提前感谢您的帮助。以下是 C++ 项目代码的一部分:

#include<iostream>
#include<string>
#include<fstream>
#include <sstream>

using namespace std;

int checkID(int idNumber)
{
    string findID;
    stringstream id_string;
    id_string << idNumber;
    findID = id_string.str();
    int offset;
    ifstream in;
    in.open("Students.txt");
    if(in.is_open())
    {
        string line;
        while(getline(in, line))
        {
            if(offset = line.find(findID, 0)!= string::npos)
            {
                cout<<"The ID already exists. Insert a different ID!"<<endl;
                return 0;
            }
        }

    }
    else
        cout<<"File doesn't exist!"<<endl;
    in.close();
}

class PERSON
{
protected:
    string name;
    string surname;
    unsigned int age;
public:
    void inputinfo()
    {
        cin>>name;
        cin>>surname;
        cin>>age;
    }
    outputinfo()
    {
        cout<<name<<endl;
        cout<<surname<<endl;
        cout<<age<<endl;
    }
};

class STUDENT: public PERSON
{
    int ID;
    float marks_sum;
    string belonging_class;

public:

    inputInfo()
    {
        cout<<"Name:";
        cin>>name;
        cout<<"Surname:";
        cin>>surname;
        cout<<"Age:";
        cin>>age;
        do
        {
            cout<<"ID:";
            cin>>ID;
        }
        while (checkID(ID)==0);

        cout<<"Sum of marks:";
        cin>>marks_sum;
        cout<<"The belonging class:";
        cin>>belonging_class;

    }


    void outputInfo()
    {
        cout<<name<<endl;
        cout<<surname<<endl;
        cout<<age<<endl;
        cout<<ID<<endl;
        cout<<marks_sum<<endl;
        cout<<belonging_class<<endl;
    }

    friend std::ostream& operator << (std::ostream& os, const STUDENT& value )
    {
        os << value.name<<" "<<value.surname<<" "<<value.age<<" "<<value.ID<<" "<<value.marks_sum<<" "<<value.belonging_class<<std::endl;
        return os;
    }
};

STUDENT student1;

int writeInFile(STUDENT studentx)
{
    ofstream os("Students.txt", ofstream::app);
    os << studentx;
    os.close();
}


int main()
{
    int opt1, opt2;
    char option;

    do
    {
        cout<<"1 -  Input data into file"<<endl<<"2 - Close program"<<endl;
        cin>>opt1;
        switch(opt1)
        {
        case 1:
            do
            {
                cout<<endl;
                cout<<"Choose one of variants"<<endl<<"1.Students"<<endl<<"2.Get back to main menu"<<endl;
                cin>>opt2;
                switch(opt2)
                {
                case 1:
                    do
                    {
                        cout<<"Do you wish to introduce a new student(Y/N)?";
                        cin>>option;
                        if(option!='N')
                        {
                            student1.inputInfo();
                            writeInFile(student1);
                        }
                    }
                    while (option!='N');
                    break;
                }

            }
            while(opt2!=2);
            break;
        }
    }
    while(opt1!=2);

}

最佳答案

#include <sstream>

using namespace std;

bool isUniqueID(ifstream& file, int id)
{

    string id_string = to_string(id);
    string currently_read_line;
    // The position of the searched key. So, in this case,
    // only the 3rd value will be tested (starting from 0).
    // John Doe 23 456
    //   |   |   |   |
    //   0   1   2   3 (the id)
    int offset = 3;

    while (getline(file, currently_read_line))
    {
        istringstream ss(currently_read_line);
        string current_entry;
        int counter = 0;

        while (ss >> current_entry) {

            if (current_entry == id_string && counter == offset) {
                cout << "The Id already exists." << endl;
                return false;
            }
            counter++;

        }
    }

    // No match found
    cout << "The ID does not exist yet." << endl;
    return true;

}

请注意:

  • 只需将打开的文件传递给该函数即可。文件只打开一次,而不是每次要检查 ID 时都打开它。
  • 这需要在 -std=c++11 中编译(用于 to_string 转换)

[更新]

偏移量变量告诉函数要测试的值。一种更一致的方法是将数据格式化为每个学生条目都有一个键/值。尽管它可以正常工作。

关于c++ - 如何检查从键盘输入的特定整数值是否存在于 C++ 文件的一行或多行中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58474943/

相关文章:

c++ - '登录': identifier not found

c++ - 在 C++ 中存储和打印 10+ 位整数

r - 将字符串拆分为固定大小的 block

c++ - 运算符重载中没有运算符 '==' 匹配

c++ - CMake + Qt,moc 编译失败,无法实现 QMetaObject 方法(编译器无法找到基本 ui 对象的 header ?)

c++ - 如何从远程计算机获取当前登录的用户名

java - 在Itext7中,我如何遍历一个字符串并查看我当前的字体是否可以正确显示该字符串?

Python 3.0 : Looping list index that is "out of range"

c++ - 使用自定义分配器及其替代方案重载基本类型

c++ - 为具有模板对象的容器类重载 operator[]