Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

c++ - No matching function - ifstream open()

This is the part of the code with an error:

std::vector<int> loadNumbersFromFile(std::string name)
{
    std::vector<int> numbers;

    std::ifstream file;
    file.open(name); // the error is here
    if(!file) {
        std::cout << "
Error

";
        exit(EXIT_FAILURE);
    }

    int current;
    while(file >> current) {
        numbers.push_back(current);
        file.ignore(std::numeric_limits<std::streamsize>::max(), '
');
    }
    return numbers;
}

And well, I kind of have no idea what is going on. The whole thing compiles properly in VS. However I need to compile this with dev cpp.

I commented out the line throwing errors in the code above. The errors are:

no matching function for call 'std::basic_ifstream<char>::open(std::string&)
no matching function for call 'std::basic_ofstream<char>::open(std::string&)

In different parts of code I get errors like numeric_limits is not a member of std, or max() has not been declared, although they exist in iostream class and everything works in VS.


Why am I getting this error?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Change to:

file.open(name.c_str());

or just use the constructor as there is no reason to separate construction and open:

std::ifstream file(name.c_str());

Support for std::string argument was added in c++11.

As loadNumbersFromFile() does not modify its argument pass by std::string const& to document that fact and avoid unnecessary copy.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...