ofstream- Writing an element into a file - C++
24,409
Yes, it's correct. It can also be simplified, for example:
#include<fstream>
#include<string>
using namespace std;
void writeValue(const char* file, int value){
ofstream f(file);
if (f)
f<<value;
}
int main()
{
string s = "text";
writeValue(s.c_str(), 12);
}
It may be more convenient in C++, to take const char* rather then char *, because string can readily be converted to const char *.
Author by
Betelgeuse
PhD in Applied Math Linear Algebra, Linear matrix inequalities, Python and Machine Learning.
Updated on July 09, 2022Comments
-
Betelgeuse almost 2 years
I want to write numbers into a file .dat in C++. I create a function, it uses ofstream. It's correct?
void writeValue(char* file, int value){ ofstream f; f.open(file); if (f.good()){ f<<value; } f.close(); }
Thanks.