【发布时间】:2013-09-21 15:47:26
【问题描述】:
我想用 C++ 将数字写入文件 .dat。我创建了一个函数,它使用ofstream。对吗?
void writeValue(char* file, int value){
ofstream f;
f.open(file);
if (f.good()){
f<<value;
}
f.close();
}
谢谢。
【问题讨论】:
-
你试过了吗?是否如您预期的那样工作?
我想用 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 *。
【讨论】:
ofstream f(file,ios::out|ios::app)并在写入每个值后添加endl:f<<value<< endl;