Search code examples
c++structgetline

I'm trying to write a char into a .txt file by using the ifstream getline function. But i get an Error Message


E0304 no instance of overloaded function "std::basic_ifstream<_Elem, _Traits>::getline [with _Elem=char, _Traits=std::char_traits]" matches the argument list

Im using a struct for the Information:

 struct customer {
    int id;
    char name;
    char phone;
    char address;
};

And im trying to write the Customers Information into a .txt file:

void customerData()
{
    ifstream ifs;
    ifs.open("Customer.txt");
    int custNum = 0;
    while (!ifs.eof())
    {
        ifs >> cust[custNum].id;
        ifs.ignore();
        ifs.getline(cust[custNum].name, 100, ';');
        ifs.getline(cust[custNum].phone, 15, ';');
        ifs.getline(cust[custNum].id, 15, ';');
        ifs.getline(cust[custNum].address, 1500);
        custNum++;
    }
}

I cant figure out how to fix the above posted Error on the getline functions.


Solution

  • There are big mistakes in your code that guys pointed out.

    1. You are not writing to the file, you are reading it.
    2. You cannot store a full name in a single character.

    Actually, if you want to store this data, you should use character array or std::string.

    So your struct will be like this :

    struct customer {
       int ID;
       char name[100];
       char phone_number[15];
       char address[1500];
       
       /*
       OR
       int ID;
       std::string name;
       std::string phone_number;
       std::string address;
       
       in this case it's better to use std::string instead of using 1500 characters for address
    
       */
    }
    

    Also, getline is not for writing to the file (as you said you want to write in file) , it is used for reading from the file.

    So your customerData function will look like this:

    //  saving in file 
    ofstream ofs(Customer.txt);
    
    //  check if file is created
    if(ofs.is_open(){
    ofs << name << '\n';
    ofs << address << '\n';
    ofs << phone_number << '\n';
    ofs << id << '\n';
    
    //  This is a simple way to store data in a file.
    //  There are other ways to store data in a file.. 
    //  I used this because you can use getline to read them and get the data as lines.
    
    }