簡體   English   中英

當我打開文件名在 std::string 中的 fstream 時,為什么會出現“無匹配函數”錯誤?

[英]Why do I get a "no matching function" error when I open an fstream with the file name in a std::string?

我正在嘗試編寫一個程序,該程序從文件中讀取字符串列表並檢查第二個文件中缺少哪些字符串並將它們打印到屏幕上。 但是,我目前在嘗試編譯時遇到錯誤。 以下是我在嘗試編譯時遇到的錯誤以及代碼。 感謝您的幫助

這是代碼:

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>

using namespace std;

ifstream IN_FILE;
ofstream OUT_FILE;

int main()  { 
    int k = 0;
    int m = 0;
    int n = 0;
    string a[5000];
    string b[5000];
    string filename;
    bool good;

    //open file and check if valid entry
    cout << "\n\nWhat is the name of the first file (ex: filename.txt)\n" << endl << "FILENAME: ";
    getline(cin, filename);
    IN_FILE.open(filename);
    while(!IN_FILE) {
        cout << "Sorry the file you entered could not be opened\n";
        cout << "\n\nWhat is the name of the first file (ex: filename.txt)\n" << endl << "FILENAME: ";
        getline(cin, filename);
        IN_FILE.open(filename);
    }

    //Read every line from file
    while(!IN_FILE.eof()) {
        getline(IN_FILE, a[k]);
        k++;
    }
    n = k;
    k = 0;
    IN_FILE.close();

    //open file and check if valid entry
    cout << "\n\nWhat is the name of the first file (ex: filename.txt)\n" << endl << "FILENAME: ";
    getline(cin, filename);
    IN_FILE.open(filename);
    while(!IN_FILE) {
        cout << "Sorry the file you entered could not be opened\n";
        cout << "\n\nWhat is the name of the first file (ex: filename.txt)\n" << endl << "FILENAME: ";
        getline(cin, filename);
        IN_FILE.open(filename);
    }

    //Read every line from file
    while(!IN_FILE.eof()) {
        getline(IN_FILE, b[k]);
        k++;
    }
    m = k;
    k = 0;
    
    //Compare the arrays and print all elements is array a that are not in array b
    for (int i = 0; i < n; i++)  { 
        int j;
        for (j = 0; j < m; j++) 
            if (a[i] == b[j]) 
                break; 
  
        if (j == m) 
            cout << a[i] << endl; 
    } 
    
    return 0; 
}

這是錯誤:

checkTester.cpp:25:26: error: no matching function for call to 'std::basic_ifstream<char>::open(std::__cxx11::string&)'
     IN_FILE.open(filename);

此構造適用於標准 C++ 11 和更新的編譯器:

std::string filename;
//...
IN_FILE.open(filename);

這基本上就是您現在擁有的代碼。 但是,上述內容不適用於預標准 C++ 11 編譯器 (C++ 98, 03)。

如果您使用預標准 C++ 11 編譯器進行編譯,那么上面的代碼應該是:

std::string filename;
//...
IN_FILE.open(filename.c_str()); // Note the null-terminated const char *

基本上,在 C++ 11 之前, std::string版本的open不存在。在 C++ 11 之前,您必須使用 C 樣式的以空字符結尾的字符串來指定名稱。

因此,您看到的錯誤是因為您在 C++ 11 之前的 C++ 版本中進行編譯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM