2016-06-28 77 views
-2

我很新的C++,我想開始對文件進行工作,所以我落得這樣做的:C++ |與文件的問題

#include <iostream> 
#include <string> 
#include <cstdlib> 
#include <windows.h> 
#include <stdexcept> 
#include <limits> 
#include <Lmcons.h> 
#include <fstream> 

using namespace std; 


void out(string x){x+="\n";cout<<x;} 
void outn(){out("");} 
void delay(int x){Sleep(x);} 
void delayS(int x){Sleep(x*1000);} 
void cs(){std::system("cls");} 
void UserName(string *x){char username[UNLEN + 1];DWORD size = UNLEN + 1;GetUserName(username, &size);string transition(username);*x=transition;} 
//use this synthax in main : char user[20];string username(user);UserName(&username); 

using namespace std; 

int main() 
{ 
char user[20];string username(user);UserName(&username); 
out(username); 
delayS(2); 
cs(); 

string beginning="C:\\Users\\" ; 
string path; 
string ending="\\Desktop\\"; 
string filename; 

out("file name = "); 
cin>>filename; 

path+=beginning; 
out(path); 
delayS(2); 

path+=username; 
out(path); 
delayS(2); 

path+=ending; 
out(path); 
delayS(2); 

path+=filename; 
out(path); 
delayS(2); 

ofstream file; 
try{ 
    file.open(path ,ios::in); 
    if(!file.is_open()){throw 404;} 
    else{ 
    file.open(path,ios::out|ios::app); 
    file<<"\n"; 
    file<<"lol";} 


    }catch(int x){cout<<"Error "<<x<<" : file not found";} 


    return 0; 
} 

這導致這個錯誤(第59行): 「爲沒有匹配功能來電 '的std :: basic_ofstream ::打開(的std :: string &,的std :: _ Ios_Openmode)'「

錯誤的圖像:https://imgur.com/YVBHDzq

我可以有一些幫助?

編輯:我使用的代碼塊16.01

回答

1

在預C++ 11,你需要傳遞一個const char*ofstream::open()作爲第一個參數:

file.open(path.c_str(), ios::in); 
+0

獲得一個新的錯誤(添加編輯對我的問題):https://imgur.com/3odU4DA –

+0

好吧,我發現^^你需要使用C字符串thingie又名:c_string() 'file.open(path.c_str(),ios: :in);' –

+0

編輯修復此問題。 – lorro