dimanche 30 avril 2017

error: no matching function for call to 'std::basic_ifstream

I am trying to write a program that opens a file and counts the whitespace-separated words in that file.

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

int main() {
    string filepath;
    cout << "Enter the file path including the file name:" << endl;
    cin >> filepath; 
    ifstream f(filepath);
    int nwords = 0;
    string word;
    while (f >> word)
        ++nwords;
    cout << "Number of words = " << nwords << endl;
}

This is the error when I try to compile it.

g++ Assignment1.cpp
Assignment1.cpp: In function 'int main()':
Assignment1.cpp:10:21: error: no matching function for call to 'std::basic_ifstream<char>::basic_ifstream(std::__cxx11::string&)'
  ifstream f(filepath);
                     ^
In file included from Assignment1.cpp:2:0:
c:\mingw\lib\gcc\mingw32\5.3.0\include\c++\fstream:495:7: note: candidate: std::basic_ifstream<_CharT, _Traits>::basic_ifstream(const char*, std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits<char>; std::ios_base::openmode = std::_Ios_Openmode]
       basic_ifstream(const char* __s, ios_base::openmode __mode = ios_base::in)
       ^
c:\mingw\lib\gcc\mingw32\5.3.0\include\c++\fstream:495:7: note:   no known conversion for argument 1 from 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' to 'const char*'
c:\mingw\lib\gcc\mingw32\5.3.0\include\c++\fstream:481:7: note: candidate: std::basic_ifstream<_CharT, _Traits>::basic_ifstream() [with _CharT = char; _Traits = std::char_traits<char>]
       basic_ifstream() : __istream_type(), _M_filebuf()
       ^
c:\mingw\lib\gcc\mingw32\5.3.0\include\c++\fstream:481:7: note:   candidate expects 0 arguments, 1 provided
c:\mingw\lib\gcc\mingw32\5.3.0\include\c++\fstream:455:11: note: candidate: std::basic_ifstream<char>::basic_ifstream(const std::basic_ifstream<char>&)
     class basic_ifstream : public basic_istream<_CharT, _Traits>
           ^
c:\mingw\lib\gcc\mingw32\5.3.0\include\c++\fstream:455:11: note:   no known conversion for argument 1 from 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' to 'const std::basic_ifstream<char>&'

Aucun commentaire:

Enregistrer un commentaire