在c++中按列向文本文件写入数据

Writing data to a text file column wise in C++

本文关键字:文件 数据 文本 c++      更新时间:2023-10-16

我是一个c++初学者。我通过一个对象数组输入了变量(属于一个类)的值。现在我如何将它们写到文本文件列明智如下??谢谢 .........

SLNO    NAME      ADDRESS        PHONE NO     TYPE      
   1.   ABC       xyzagsgshsh    27438927     Mobile
   2.   QWE       qwhjbbdh       78982338     Landline

这是我存储数据的代码。我如何使它成为一个文本文件的内容如下?

#include<iostream>
#include<string>
#include<fstream>
using namespace std;
class emp
{
    string name,address,phone,type;
    public:
    void getdata();
}obj[5];
void emp::getdata()
{
    cout<<"nEnter the details:";
    cout<<"nName: ";cin>>name;
    cout<<"Address:";
    cin>>address;
    cout<<"Phone number: "; cin>>phone;
    cout<<"nType of phone? (Landline/Mobile) :";
    cin>>type;
}
int main()
{
    ofstream ptr;
    ptr.open("Phone.dat",ios::out);
    cout<<"nEnter the no.of.records: ";
    int n,i;
    cin>>n;
    for(i=0;i<n;i++)
    {
        obj[i].getdata();
        ptr.write((char*)&obj[i],sizeof(obj[i]));
    }
    return 0;
}

既然已经创建了一个文件流,那么可以利用输出标志(std::left、std::right和std::setw):

http://www.cplusplus.com/reference/iomanip/setw/

http://www.cplusplus.com/reference/ios/left/

现在,为了确保存储在emp类的任何对象中的任何字符串都不会超过通过std::setw分配给ofstream/ostream的大小,可以使用string::resize.

可以使用字符串/文件流、换行符和std::setw

ofstream myfile;
myfile.open ("example.txt");
myfile << "SLNO" << std::setw(10) << "NAME" << std::setw(10) << "ADDRESS" << std::setw(10) << "PHONE NO" << std::setw(10) << "TYPEn";

这将用10-text lenght空格分隔所有文本并将其放入example.txt

记得检查文件的有效性并关闭文件

这取决于上下文。用于简单地输出到控制台窗口(或者如果你有一个固定宽度的字体在别处,但那是相当罕见),您可以在每个元素之前使用std::setw,指定字段的宽度。对于文本(std::string),然而,通常使用resize更容易,并将其设置为一开始的尺寸是正确的。