我想用 C++ 将数字写入 .dat 文件。我创建了一个函数,它使用 ofstream。这是正确的吗?
void writeValue(char* file, int value){
ofstream f;
f.open(file);
if (f.good()){
f<<value;
}
f.close();
}
谢谢。
最佳答案
是的,这是正确的。还可以简化,例如:
#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);
}
在 C++ 中,采用 const char* 而不是 char * 可能更方便,因为字符串可以轻松转换为 const char *。
关于c++ - ofstream- 将元素写入文件 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18934538/