【问题标题】:ofstream- Writing an element into a file - C++ofstream - 将元素写入文件 - C++
【发布时间】: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++ c file ofstream


【解决方案1】:

是的,没错。也可以简化,例如:

#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)并在写入每个值后添加endlf&lt;&lt;value&lt;&lt; endl;
  • @Betelgeuse "It doesn't work" 不是错误描述。预期的行为是什么,观察到的行为是什么?你是如何观察到这种行为的?
  • 我想将新值追加到文件中。但是虽然我以追加模式打开文件,但之前的值被覆盖了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多