2017-02-03 3 views
1

사용자 입력을 기반으로 파일을 여는 프로그램을 만들려고합니다. Here`s 내 코드 :사용자 입력을 기반으로 파일 열기 C++

#include <iostream> 
#include <fstream> 
#include <string> 
using namespace std; 

int main() { 

    string filename; 
    ifstream fileC; 

    cout<<"which file do you want to open?"; 
    cin>>filename; 

    fileC.open(filename); 
    fileC<<"lalala"; 
    fileC.close; 

    return 0; 
} 

그러나 나는 그것을 컴파일 할 때, 그것은 나에게이 오류 제공 :

[Error] no match for 'operator<<' (operand types are 'std::ifstream {aka std::basic_ifstream<char>}' and 'const char [7]') 

사람이이 문제를 해결하는 방법을 알고 있나요을? 감사합니다 ...

+0

봐 :

그래서 올바른 코드는 다음과 같다. –

+4

... 대신'std :: ofstream'을 사용하십시오. –

답변

5

코드에 몇 가지 문제가 있습니다. 먼저, 파일에 쓰려면 ofstream을 사용하십시오. ifstream은 파일 읽기 전용입니다.

두 번째로 열린 메서드는 string이 아닌 char[]입니다. C++에서 문자열을 저장하는 일반적인 방법은 string을 사용하는 것이지만 char 배열에도 저장할 수 있습니다. char[]string을 변환하려면 c_str() 방법을 사용하십시오 fileC.close()를 : 괄호가 필요하므로

fileC.open(filename.c_str()); 

close 방법은 방법이 아닌 속성입니다. `표준 : ifstream`의 문서에서

#include <iostream> 
#include <fstream> 
#include <string> 
using namespace std; 

int main() { 
    string filename; 
    ofstream fileC; 

    cout << "which file do you want to open?"; 
    cin >> filename; 

    fileC.open(filename.c_str()); 
    fileC << "lalala"; 
    fileC.close(); 

    return 0; 
} 
2

ifstream입력 용이기 때문에 쓸 수 없습니다. ofstream (출력 파일 스트림)에 쓸 수 있습니다.

cout << "which file do you want to open?"; 
cin >> filename; 

ofstream fileC(filename.c_str()); 
fileC << "lalala"; 
fileC.close(); 
+0

그것은 여전히 ​​내게이 오류를 준다. [std :: basic_ofstream :: basic_ofstream (std :: string &) '에 대한 호출과 일치하는 함수가 없다는 오류 [오류] – Hillman

+0

@Hillman 실수로'std :: ofstream'의 생성자는' const char *'대신'std :: string'을 사용합니다. 따라서 파일 이름에서'.c_str()'을 호출하십시오. – CoryKramer

+0

오케이 작업 :-D 감사합니다. – Hillman