c++ - 错误 : no matching function for call to 'std::basic_ifstream<char>::basic_ifstream(std::__cxx11::string&)'

标签 c++ c++11

我正在尝试编写一个程序来打开一个文件并计算该文件中以空格分隔的单词数。

#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;
}

这是我尝试编译时的错误。

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>&'

最佳答案

g++ -std=c++11 Assignment1.cpp

应该可以。问题是这些年来 C++ 有不同的标准。标准混杂。根据我的经验,你在编译时看到的 90% 的错误都与 ios 有关,要么是用 gcc 编译的,要么是标准错误。抱歉,我不能确定;我不使用 Windows。

关于c++ - 错误 : no matching function for call to 'std::basic_ifstream<char>::basic_ifstream(std::__cxx11::string&)' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43712736/

相关文章:

c++ - 调用类友元函数的类成员函数(都是同一个类)可能吗?

java - java中通过引用传递一个整数

c++ - 最快的算法计算数组中 3 个长度 AP 的数量

c++ - 为什么 delete[] 不等同于为 C++ 中的每个元素调用 delete?

c++ - 将多个参数传递给线程函数

c++ - 如何与 CRTP 一起使用?

c++ - 将新元素插入/放置到 unordered_map/unordered_set 时的提示

c++ - C/C++ iTunes API 在哪里? (不是 COM!)

c++ - 'int [0]' c++ 的初始值设定项太多

algorithm - 向量中的最小值,跳过一些索引