2009-07-21 9 views
3

같이, 나는 C를 배우고 ++와 나는이 ifstream 방법에 문자열를 사용하기 위해 노력하고있어 몇 가지 문제를 얻고 문자열을 넣어 여기에 전체 코드입니다 :ifstream 방법

// obtaining file size 
#include <iostream> 
#include <fstream> 
using namespace std; 

int main (int argc, char** argv) 
{ 
    string file; 
    long begin,end; 
    cout << "Enter the name of the file: "; 
     cin >> file; 
    ifstream myfile (file); 
    begin = myfile.tellg(); 
    myfile.seekg (0, ios::end); 
    end = myfile.tellg(); 
    myfile.close(); 
    cout << "File size is: " << (end-begin) << " Bytes.\n"; 

    return 0; 
} 

는 그리고 여기 이클립스의 오류, 방법 전에 X입니다 :

no matching function for call to `std::basic_ifstream<char, std::char_traits<char> >::basic_ifstream(std::string&)' 

그러나 이클립스에서 컴파일하려고하면 구문 앞에 오류가 있음을 나타내지 만 구문에 무엇이 잘못 되었나요? 메서드 앞에 x을 넣으시겠습니까? 감사!

+0

당신이지고있는 오류에 대한 자세한 정보를 제공 할 수 있을까요? 아니면 완전한 샘플을 게시 할 수 있습니다 ... –

+0

어쩌면 fstream가 포함되어 있지 않습니까? 전체 코드를 입력하십시오 – CsTamas

+0

정확한 헤더를 포함 시켰습니까? – mdec

답변

8

char* ~ ifstream 생성자에 c_str() 함수를 전달해야합니다.

// includes !!! 
#include <fstream> 
#include <iostream> 
#include <string> 
using namespace std; 

int main() 
{ 
    string filename; 
    cout << "Enter the name of the file: "; 
    cin >> filename; 
    ifstream file (filename.c_str()); // c_str !!! 
} 
+0

대단히 감사합니다 jia3ep !!!!!!!!!!!!! –

5

문제는 ifstream의 생성자 문자열을 허용하지 않는다는 것입니다,하지만 C 스타일 문자열 :

explicit ifstream::ifstream (const char * filename, ios_base::openmode mode = ios_base::in); 

그리고 std::string는 C 스타일 문자열로 암시 적 변환이 없습니다, 그러나 명시 적으로 하나 c_str() .

사용 :

... 
ifstream myfile (file.c_str()); 
...