2012-11-13 4 views
0

간단한 데이터베이스 프로그램을 작성하려고했습니다. 문제는 ofstream이 새 파일을 만들고 싶지 않다는 것입니다.Ofstream이 새 파일을 올바르게 작성하지 않음

다음은 문제의 코드에서 발췌 한 것입니다.

void newd() 
{ 
string name, extension, location, fname; 
cout << "Input the filename for the new database (no extension, and no backslashes)." << endl << "> "; 
getline(cin, name); 
cout << endl << "The extension (no dot). If no extension is added, the default is .cla ." << endl << "> "; 
getline(cin, extension); 
cout << endl << "The full directory (double backslashes). Enter q to quit." << endl << "Also, just fyi, this will overwrite any files that are already there." << endl << "> "; 
getline(cin, location); 
cout << endl; 
if (extension == "") 
{ 
    extension = "cla"; 
} 
if (location == "q") 
{ 
} 
else 
{ 
    fname = location + name + "." + extension; 
    cout << fname << endl; 
    ofstream writeDB(fname); 
    int n = 1; //setting a throwaway inteher 
    string tmpField, tmpEntry; //temp variable for newest field, entry 
    for(;;) 
    { 
     cout << "Input the name of the " << n << "th field. If you don't want any more, press enter." << endl; 
     getline(cin, tmpField); 
     if (tmpField == "") 
     { 
      break; 
     } 
     n++; 
     writeDB << tmpField << ": |"; 
     int j = 1; //another one 
     for (;;) 
     { 
      cout << "Enter the name of the " << j++ << "th entry for " << tmpField << "." << endl << "If you don't want any more, press enter." << endl; 
      getline(cin, tmpEntry); 
      if (tmpEntry == "") 
      { 
       break; 
      } 
      writeDB << " " << tmpEntry << " |"; 
     } 
     writeDB << "¬"; 
    } 
    cout << "Finished writing database. If you want to edit it, open it." << endl; 
} 
} 

편집 : OK, 단지

#include <fstream> 
using namespace std; 
int main() 
{ 
ofstream writeDB ("C:\\test.cla"); 
writeDB << "test"; 
writeDB.close(); 
return 0; 
} 

을 시도하고 접근 권한 문제입니다 그래서, 작동하지 않았다.

+0

은 프로그램 실행 예제와 입력 내용을 제공합니다. –

+1

또한이 방법으로 문자열을 입력 할 때 "이중 백 슬래시"가 필요하지 않으며 코드의 문자열 리터럴에 대해서만 필요합니다. – HerrJoebob

+5

소스를 줄이면 문제가 표시됩니다. 그런 다음 실제로 이것이 * 문제인지 확인하십시오. 내가 생각하기에, 당신은 존재하지 않는 재미있는 장소에서 파일을 열려고합니다. 'std :: ofstream'이 예상대로 작동하는지 확인하는 간단한 프로그램은 다음과 같습니다 :'#include int main() {std :: ofout out ("empty.txt"); }'. 거기에서부터 생성 된 파일의 생성이 중단되었는지 확인하십시오. –

답변

3
ofstream writeDB(fname); //-> replace fname with fname.c_str() 

당신은 ofstream 생성자의 문서를 조회하는 경우, 당신은 같은 것을 볼 수 있습니다 : 명시 ofstream을 (const를 숯불 * 파일 이름, ios_base :: openmode 모드 = ios_base :: 아웃);

두 번째 인수는 선택 사항이지만 첫 번째 인수는 const char *이며 문자열이 아닙니다. 이 문제를 해결하기 위해 가장 간단한 방법은 문자열을 C- 문자열 (char *, 기본적으로 char 배열 임)으로 변환하는 것입니다. 그렇게하려면 c_str() (라이브러리의 일부)을 사용하십시오.

그 외의 경우에는 정보를 C-str에 직접 배치 한 다음 정상적으로 스트림 생성자에 전달할 수 있습니다.

+4

C++ 11은'std :: string' 인수를 취하는 [constructor] (http://en.cppreference.com/w/cpp/io/basic_ofstream/basic_ofstream)을 추가합니다. 그러나 OP가 더 오래된 컴파일러는 코드를 컴파일해서는 안됩니다. – Praetorian

+0

고마워, 내가 추가했지만 여전히 작동하지 않습니다. Visual Studio Express 2012 BTW를 사용하고 있습니다. 모두에게 감사드립니다! –