简体   繁体   中英

C++. How to write to file from function

I have function what must write something in file.

I try it this way:

int main() {
    std::ofstream fout;
    fout.open("OUTPUT.TXT");
    i = searchLexemes(input, i, 1, fout);
}

searchLexemes is defined this way:

int searchLexemes(std::string value, int i, int type, std::ofstream fout);

If i call searchLexemes like i do in main(), Visual Studio gives me error:

IntelliSense: "std::basic_ofstream<_Elem, _Traits>::basic_ofstream(const std::basic_ofstream<_Elem, _Traits>::_Myt &_Right) [с _Elem=char, _Traits=std::char_traits]" (объявлено в строке 1034 из "C:\\Program Files\\Microsoft Visual Studio 11.0\\VC\\include\\fstream") недоступно c:\\Users\\Badina\\Documents\\Visual Studio 2012\\Projects\\PLT lab1\\PLT lab1\\Исходный код.cpp 191 33 PLT lab1

I'm using russian version of VS 2012, but i guess problem must be clear.

Use reference to declare your function like so:

int searchLexemes(const std::string& value, int i, int type, std::ofstream& fout);

The reason you've got this error is because std::ofstream does not have a public copy constructor (eg: ofstream(const ofstream& rhs) ), or one is explicitly marked as delete d in C++11.

You should have the function call fout.open, pass in the name of the file.

But if you really want to then,

int searchLexemes(std::string value, int i, int type, std::ofstream *fout);
int main() {
    std::ofstream fout;
    fout.open("OUTPUT.TXT");
    i = searchLexemes(input, i, 1, &fout);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM