我有这个程序,它将一个人的名字和姓氏写入文件。
当我打开文件查看其内容时,单词就在彼此旁边,它们之间没有任何空格。例如,如果输入是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;
}
答案 0 :(得分: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个字符宽的字段,同时保持左对齐。