【问题标题】:how to take input of an int variable and write it to a file?如何获取 int 变量的输入并将其写入文件?
【发布时间】:2015-11-14 07:41:01
【问题描述】:

我知道如何初始化一个 int 变量并将其写入文件,但是如何将此 int 变量作为用户的输入,将其写入文件然后读取它? 我认为应该按如下方式完成,但是当我打开要写入的文件时,它只有字符串类型变量“name”和一些非人类可读的代码,而不是 int 变量“age”。 这里的 program 是类的名称,具有 name 和 age 属性。

   void save()
{
    ofstream out;
    out.open("program.txt", ios::out | ios::binary | ios::app);
    if (!out)
        cout << "cannot save";
    else
    {
        program *temp = first;
        while (temp != NULL)
        {
            out.write( (char)*temp, sizeof(program));
            temp = temp->next;

        }
        out.close();
    }
}

【问题讨论】:

  • 请始终如一地格式化您的代码并删除任何不必要的内容。此外,将 C++ 标签添加到您的问题中以获得适当的可见性。

标签: c++ oop fwrite


【解决方案1】:

您正在以二进制模式将自定义对象类型写入文件。您看到的是一个包含program 类型对象的文件。

如果您想要人类可读的文件输出,请尝试写入不带ios::binary 的文件。但请记住,您不能将对象写入文件。您必须获取对象中的各个成员并编写它们。

希望我说得通。

以这个程序为例。这行得通。

# include <string>
# include <fstream>
# include <iostream>

using namespace std;

struct program {
    int age;
    string name;
    program* next;
};

program* first = new program;

void save()
{
    ofstream out;
    out.open("program.txt", ios::out | ios::app);
    if (!out)
        cout << "cannot save";
    else
    {
        program *temp = first;
        while (temp != NULL)
        {
            out<<temp->age<<" "<<temp->name<<"\n";
            temp = temp->next;

        }
        out.close();
    }
}

int main()
{
    first->age=10; first->name="Alice"; 
    first->next = new program;
    first->next->age=20; first->next->name="Bob"; first->next->next = NULL;       
    save();
    return 0;
}

【讨论】:

  • @Zeb :我已经编辑了答案以包含一个示例程序。这就是你的写作方式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-16
相关资源
最近更新 更多