문제

이 질문은 이미 여기에 답이 있습니다.

나는 C ++를 배우고 있고 내가 사용하려고 할 때 약간의 문제가 있습니다. 안에 ifstream 다음과 같은 방법 :

string filename;
cout << "Enter the name of the file: ";
   cin >> filename;
ifstream file ( filename );

전체 코드는 다음과 같습니다.

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

그리고 여기에 일식의 오류가 있습니다. 엑스 방법 전에 :

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

하지만 일식을 컴파일하려고 할 때 엑스 이 방법 전에는 구문의 오류를 나타내지 만 구문에서 무엇이 잘못 되었습니까? 감사!

도움이 되었습니까?

해결책

당신은 통과해야합니다 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 !!!
}

다른 팁

문제는 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() );
...
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top