简体   繁体   中英

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"). 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.

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"). 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). I don't know to search in the string for the value of ID only. 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. 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). 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++:

#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. The file is opened once, instead of opening it every time you want to check an ID.
  • This requires to compile in -std=c++11 (for the to_string conversion)

[Update]

The offset variable tells the function what value to test for. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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