简体   繁体   English

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

[英]How to check if a specific integer value input from keyboard exist in a line or more lines of a file in C++

I have a small project for a C++ course and I'm stuck trying to check if a value of a data member of STUDENT's class exists in the file(the "ID").我有一个 C++ 课程的小项目,我一直在尝试检查文件中是否存在学生的 class 的数据成员的值(“ID”)。 I've tried to use some function that I found on the internet to transform the integer value I'm searching for into a string and then use the find function, to search for it in each line of the file.我尝试使用我在互联网上找到的一些 function 将我正在搜索的 integer 值转换为字符串,然后在文件的每一行中使用 find ZC1C425268E68385D1AB5074C17A94F1 来搜索它。

It works, but whenever I check one line from the file, it gets false pozitive, because the ID value(for example "12") is for example, identical to the value of age(also "12").它可以工作,但是每当我检查文件中的一行时,它都会得到错误的结果,因为 ID 值(例如“12”)与年龄的值(也是“12”)相同。 It does that because the age value comes before the ID value in my file and also in the string variable (and I can't change it).这样做是因为年龄值在我的文件和字符串变量中的 ID 值之前(我无法更改它)。 I don't know to search in the string for the value of ID only.我不知道只在字符串中搜索 ID 的值。 I use the function "inputInfo" to input student1's member values from the keyboard, and function "checkID" to check if value of "ID" already exists in the file.我使用 function "inputInfo" 从键盘输入 student1 的成员值,并使用 function "checkID" 检查文件中是否已经存在 "ID" 的值。 Also, for another aspect of the project, I am seeking a way to search for occurrence of the ID and name data members values in the same file(once they are already written).此外,对于项目的另一个方面,我正在寻找一种方法来搜索同一文件中出现的 ID 和名称数据成员值(一旦它们已经被写入)。 One solution I've thought is to somehow start the search after the occurence of another character(for example the space character, given the fact that in the file, each field is delimited from another with a space), but I'm not sure the find function is able to do that.Thank you in advance for your help.Below is a part of the project's code in C++:我认为的一个解决方案是在另一个字符出现后以某种方式开始搜索(例如空格字符,因为在文件中,每个字段都用空格与另一个字段分隔),但我不确定找到 function 能够做到这一点。提前感谢您的帮助。以下是 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;

}

Please note:请注意:

  • Just pass your opened file to the function.只需将打开的文件传递给 function。 The file is opened once, instead of opening it every time you want to check an ID.该文件只打开一次,而不是每次您要检查 ID 时都打开它。
  • This requires to compile in -std=c++11 (for the to_string conversion)这需要在 -std=c++11 中编译(用于 to_string 转换)

[Update] [更新]

The offset variable tells the function what value to test for.偏移变量告诉 function 要测试什么值。 A more consistent way to do this, would be to format the data as to have a key/value for each student entry.一种更一致的方法是将数据格式化为每个学生条目都有一个键/值。 It works as it though.它虽然工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM