在c++中按列向文本文件写入数据
Writing data to a text file column wise in C++
我是一个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
更容易,并将其设置为一开始的尺寸是正确的。
相关文章:
- 从 bmp 文件数据创建 MFC CBitmap
- 从存储为 Windows 资源 (c++) 的 png 中获取 png 文件数据
- 如何在 Gnuplot 中分别绘制 2 个文件数据?我有一个文件"sin.txt",另一个文件"cos.txt",我想将它们分别绘制在一个图表上
- 获取文件数据预处理器宏
- 错误的值是使用c++从CSV文件数据写入数组
- 无法在可视C++中检索资源文件数据
- 将文本文件数据读入字符数组时提取运算符的歧义
- 如何使用curl c ++源代码发布wav文件数据,如何使用c ++使用--data-binary?
- 如何在C++中读取 UTF-8 文件数据
- 如何在结构中存储二进制文件数据
- 无法从 turbo c 程序中的文件检索文件数据
- 使用 fstream 将文件数据从当前位置保存到文件末尾
- 通过Google Protobuf发送二进制文件数据
- 在通过套接字向服务器发送文件数据时,我得到了一些垃圾值?为什么
- 如何使用dlang读取二进制文件数据
- 程序使用FSCANF读取文件数据后崩溃
- 检测二进制文件数据的端性
- C++ 从文本文件数据类型读取为结构,并将数据存储在列表的向量中
- 将 FFT 应用于 WAV 文件数据的 C++
- C++内存映射的文件数据预取