如何获取int变量的输入并将其写入文件
how to take input of an int variable and write it to a file?
我知道如何初始化一个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;
}
相关文章:
- 用c++从输入文件中读取另一行
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 获取通过重定向传入的输入文件的名称?
- C++ 如何打开带有另一个目录的输入文件?
- C++模板编程设计问题 - 根据输入文件返回不同的类型
- 如何从输入文件 c++ 创建随机名称生成器
- 从输入文件修剪空格
- 链接器输入文件未使用,因为链接未完成,我无法获得.o
- 我正在尝试从输入文件中读取,然后使用它们的子字符串比较字符串的特定部分
- 我遇到使用 c++ 逐行读取输入文件的问题
- 使用重定向命令从 stdin 读入的字符串"<"输入文件未正确附加
- 使用 getline 从输入文件打印时如何忽略空白行
- 如何按升序对输入文件中的数字进行排序,并找到它们的范围和中值
- 数组大小由输入文件中的行数定义
- 从C++输入文件读取
- 在课堂上创建了一个朋友,给出"无输入文件"错误
- 通过显示一行星号来创建条形图,该条形图将读取数据的输入文件
- 利用输入文件中的数据(字符串和int)并在循环中利用
- C++ 仅读取输入文件中的部分(不是全部)数据以添加到记录中
- 如何从输入文件中读取字符并将其存储到向量中?