Home > Software design >  I'm trying to read a file into a vector and keep getting this error
I'm trying to read a file into a vector and keep getting this error

Time:10-24

I keep getting this error:

 error: no match for ‘operator>>’ (operand types are ‘std::ifstream’
 {aka ‘std::basic_ifstream<char>’} and ‘std::vector<symbol>’)
   26 |             myFile >> temp;
      |             ~~~~~~ ^~ ~~~~
int readAlphabetFromFile(string filename, vector<symbol> alphabet) {
    ifstream myFile;
    myFile.open(filename);
    if (myFile.is_open()) {
        while (!myFile.eof()) {
            vector<symbol> temp;
            myFile >> temp;
            alphabet.push_back(temp);
        }
        return 0;
    }
    else {
        return -1;
    }
}

CodePudding user response:

myFile >> temp;

In C an overloaded >> operator is defined for just a few elementary types and classes; namely it's defined for all numerical and floating point types, std::string, and a few other simple things.

This temp is a std::vector of some unknown type named symbol.

There is no defined overload of the >> operator for a vector of anything. Additionally if you defined a class named symbol there's not going to be a >> overload of that, either.

while (!myFile.eof()) {

Another problem with the shown code is that this is always a bug.

There are very few things in C that work by default. If your goal is to read a vector of these symbols, whatever they are, you will need to write all the logic and all the code to do that, step by step, all by yourself. C will not do it for you. You will also need to use appropriate logic for checking for an end of file condition, as explained in the preceding link.

CodePudding user response:

The error message is telling you that the compiler can't find an operator>> for reading a std::vector from a std::ifstream, which is true.

However, alphabet is a vector of symbols, so you need to push symbol objects into it, but you are trying to push another vector instead. You need to change vector<symbol> temp; to just symbol temp; and then implement operator>> for symbol.

Also, alphabet needs to be passed in to your function by reference or pointer, but you are passing it in by value, so you are acting on a copy of the caller's vector, not the original.

Also, while (!myFile.eof()) is a logic error that needs to be fixed: Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?

Try this instead:

istream& operator>>(istream &in, symbol &sym) {
    // read from 'in' into 'sym' as needed...
    return in;
}

int readAlphabetFromFile(string filename, vector<symbol> &alphabet) {
    ifstream myFile(filename);
    if (myFile.is_open()) {
        symbol temp;
        while (myfile >> temp) {
            alphabet.push_back(temp);
        }
        return 0;
    }
    else {
        return -1;
    }
}
  • Related