【问题标题】:Error: No matching function?错误:没有匹配的功能?
【发布时间】:2016-05-26 23:23:48
【问题描述】:

问题是,我不断收到此错误 > 错误:没有匹配函数调用 'std::basic_ifstream::basic_ifstream(std::basic_string)'

and >error: no matching function for call to 'std::basic_ofstream::open(std::basic_string)'

我该如何解决这个问题?

#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>

using namespace std;

bool loginOn(){

string username, password, un, pw;
cout << "Username > ";
cin >> username;
cout << "Password > ";
cin >> password;

ifstream read("c:\\" + username + ".txt");
getline(read, un);
getline(read, pw);

if ( un == username && pw == password){
    return true;
}
else{
    return false;
}
}

int main(){

int choice;

cout << "1: Register" << endl;
cout << "2: Login" << endl;
cout << "Your chouce > ";
cin >> choice;

if (choice == 1){

    string username, password;
    cout << "Choose username > ";
    cin >> username;
    cout << "Choose password > ";
    cin >> password;

    ofstream file;
    file.open("c:\\" + username + ".txt");
    file << username << endl << password;
    file.close();

    main();
}
else if (choice == 2){
    bool status = loginOn();

    if (!status){
        cout << "Wrong login information" << endl;
        system("PAUSE");
        return 0;
    }
    else{
        cout << "Congratulation! You've login successfully" << endl;
        system("PAUSE");
        return 1;
    }
}
}

【问题讨论】:

  • 你确定你启用了-std=c++11
  • 试试file.open(std::string("c:\\") + username + ".txt");
  • @πάνταῥεῖ 如何启用它?
  • @πάνταῥεῖ file.open(std::string("c:\\") + username + ".txt"); - 给了我另一个错误
  • @πάνταῥεῖ 启用 -std=c++11 已修复

标签: c++ c++11


【解决方案1】:

您的编译器似乎没有默认启用当前标准。在c++11标准之前std::ifstream::open()只带了const char*参数。

正如我在评论中提到的,使用 -std=c++11 编译器标志(或任何适合您的编译器的选项)启用当前标准。

【讨论】:

    【解决方案2】:

    fstream::open 采用 const char*,而不是字符串。在参数上调用 .c_str():

    file.open(("c:\\" + username + ".txt").c_str());
    

    http://www.cplusplus.com/reference/fstream/fstream/open/

    【讨论】:

    • 在现行标准之前,是的。
    • OP 的编译器错误清楚地表明现代重载的缺乏。
    猜你喜欢
    • 2014-03-03
    • 1970-01-01
    • 1970-01-01
    • 2021-01-11
    • 2020-07-07
    • 1970-01-01
    • 2014-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多