Home > OS >  My getline function doesn't seem to be working
My getline function doesn't seem to be working

Time:12-08

Sorry, still a beginner to coding.

I have this included in the block of code.

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

Basically, I'm attempting to create a function that will store line by line, the data into a structure with 4 arrays of [200]. Here is my code,

struct AccountInfo {
    string account[200];
    int pin[200];
    string name[200];
    long double ammount[200];
};

AccountInfo storeAccount(AccountInfo tabs[]) {
    ifstream myfile;
    myfile.open("AccountInfo.txt");
    for (int i = 0; i < myfile.eof(); i  )
    {
     getline(myfile, tabs[i].account);
     getline(myfile, tabs[i].pin);
     getline(myfile, tabs[i].name);
     getline(myfile, tabs[i].ammount);
    }
}

All my getline's have this error message "Severity Code Description Project File Line Suppression State Error (active) E0304 no instance of overloaded function "getline" matches the argument list"

If someone can help me out, that would be fantastic!

CodePudding user response:

The getline() function needs to receive in the second argument an std::string. The compiler tells you that there is no such function that matches the argument list you've provided:

These are not strings:

  1. array of string
  2. array of int
  3. array of long double

Also, when you pass a C-array to a function, it is recommended to pass its size, so if you iterate it internally, you could check that you're not exceeding its boundaries.

CodePudding user response:

Instead of having a struct of 4 arrays[200], you should create a struct of single values and then an array of AccountInfo[200]. This is what your method uses.

The code should look something like this:

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

using namespace std;

struct AccountInfo {
    string account;
    int pin;
    string name;
    long double ammount;
} AcountInfo_[200];

void storeAccount(AccountInfo tabs[]) {
    ifstream myfile;
    myfile.open("AccountInfo.txt");
    for (int i = 0; i < myfile.eof(); i  )
    {
     string pin;
     string amount;
     getline(myfile, tabs[i].account);
     getline(myfile, pin);
     tabs[i].pin = stoi(pin);
     getline(myfile, tabs[i].name);
     getline(myfile, amount); 
     tabs[i].ammount = stof(amount);
    }
}

CodePudding user response:

scanf() might be an easier option.

freopen("AccountInfo.txt", "r", stdin);
AccountInfo storeAccount(AccountInfo tabs[]) {
   for (int i = 0; i < myfile.eof(); i  ) {
      scanf(myfile, &tabs[i].account);
      scanf(myfile, &tabs[i].pin);
      scanf(myfile, &tabs[i].name);
      scanf(myfile, &tabs[i].ammount);
   } 
}
  • Related