用于存储在文件中的单词的固定大小

fixed size for words for storing in a file

本文关键字:单词 用于 文件 存储      更新时间:2023-10-16

我有一个程序,它将一个人的名字和姓氏写入文件
当我打开文件查看其内容时,这些单词就在一起,没有任何空格。例如,如果输入是Bill和Gates,则这些单词存储在文件中,如下所示:

BillGates

但我想把它们存储为两个单独的单词,每个单词都有固定的字段长度。就像这样。

Bill      Gates     
--------------------

每个单词占用10个单位的空间。怎么做?这是节目。

#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
class Person
{
    public:
    char fname[11];
    char lname[11];
};
ostream & operator << (ostream & obj,Person & p)
{
    obj << p.fname << p.lname;
    return obj;
}
int main()
{
    ofstream ofile("person.txt");
    Person P;
    cout << "Enter details n";
    cin >> P.fname >> P.lname;
    ofile << P;
    ofile.close();
    return 0;
}

您可以设置输出值的宽度。为了保持左边的格式,您可以设置输出流的格式标志。示例如下:

int main()
{
   ofstream ofile("person.txt");
   Person P;
   cout << "Enter details n";
   cin >> P.fname >> P.lname;
   ofile.setf(ofile.left);
   ofile.width(10);
   ofile << P.fname;
   ofile << P.lname;
   ofile.close();
   return 0;
}

这将为您提供10个字符宽的字段,同时保持左对齐。