如何获取int变量的输入并将其写入文件

how to take input of an int variable and write it to a file?

本文关键字:输入 文件 变量 何获取 获取 int      更新时间:2023-10-16

我知道如何初始化一个int变量并将其写入文件,但如何将这个int变量作为用户的输入,将其写入到文件中,然后读取它?我认为应该按如下方式进行,但当我打开正在编写的文件时,它只有字符串类型的变量"name"和一些非人类可读的代码,而不是int变量"age"。这里的程序是具有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();
    }
}

您正在以二进制模式向文件写入自定义对象类型。您看到的是一个包含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;
}