Search code examples
c++compiler-errorsfstreamifstream

C++ compile error


#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    ifstream inputFile;
    string example;
    int numbers,
    totalNumbers = 0;

    // Prompt user to input name of the file to open
    cout << "Please enter the name of the program" << endl;
    cin >> example;

    // Open the input file that is assigned to the variable 'example'
    inputFile.open(example.c_str());

    // If the file successfully opened, process it
    if(inputFile)
    {
        // Loop until the EOF is reached
        while(inputFile >> numbers) // If a value was read
        {
            totalNumbers += numbers;
        }

        // Close the file
        inputFile.close(example.c_str());

        cout << totalNumbers;
    }
    else 
    {
        // Display an error message
        cout << "could not access file";
    }

    return 0;
}

The error is as follows:

fileAdder.cpp: In function ‘int main()’: fileAdder.cpp:36:40: error: no matching function for call to ‘std::basic_ifstream::close(const char*)’ inputFile.close(example.c_str()); ^ fileAdder.cpp:36:40: note: candidate is: In file included from fileAdder.cpp:8:0: /usr/include/c++/4.8.2/fstream:576:7: note: void std::basic_ifstream<_CharT, _Traits>::close() [with _CharT = char; _Traits = std::char_traits] close() ^ /usr/include/c++/4.8.2/fstream:576:7: note: candidate expects 0 arguments, 1 provided


Solution

  • Remove example.c.str()

    The correct statment will be:

    inputFile.close();
    

    We do not need to pass the parameter