2017-05-04 139 views
0

这是包含我无法修复的错误的代码。 我的代码打开文本文件似乎是错误的,但我试图看看它有什么问题,但无法找到它。我有类似的程序,这个代码可以工作,但这不是。错误:没有用于调用ifstream :: open(string)的匹配函数

错误: 用于调用 '的std :: basic_ifstream ::开(STD :: __ cxx11 :: string的&)' 不匹配函数 FILE.open(文件名)< ---

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

using namespace std; 

#include "nameSort.h" 

size_t readNames(string filename, string surnames[], string firstnames[]) 
{ 
    //initialize size top 0 
    size_t SIZE = 0; 

    //open file for input 
    ifstream FILE; 
    FILE.open(filename);//(This is where the error is) 

    //check if file exists 
    if(!FILE) 
    { 
    cout << "Error! No such file!\n"; 
    return 0; 
    } 
    else 
    { 
     //read file data to arrays 
     while(!FILE.eof()) 
     { 
     FILE >> firstnames[SIZE] >> surnames[SIZE]; 
     SIZE++; 
     }//end while 
    }//end if 

    FILE.close(); 
    return size; 
} 
+1

您是否正在编译至少启用C++ 11? –

+0

它在我插入文本文件名称而不是变量时起作用,是否有人知道为什么我会在变量中出现错误? –

+1

尝试'FILE.open(filename.c_str());',但更好地启用C++ 11 – user463035818

回答

0

在C++ 11中添加了过载std::basic_ifstream::open(const std::string&)。它是C++中不太好用的功能之一,许多函数都以​​C字符串作为参数,而使用std::string通常是首选。这在C++ 11中通过添加该过载来解决某些功能。

您可能没有启用C++ 11。只是另一个怪癖......尽管C++ 11已经存在很长一段时间,但你仍然必须明确地告诉编译器使用-std=c++11标志来启用它。

作为一种变通方法,您可以使用

FILE.open(filename.c_str()); 

并请考虑使用小写的变量名。所有大写变量名通常不被认为是良好的做法。

相关问题