【发布时间】:2015-09-30 10:22:55
【问题描述】:
我已经创建了一类医生,我想在记事本文件(Doctor.txt)中插入医生的数据,但数据没有对称性,因为我的输入在行中没有固定长度...
int DocID;
string Name,Department,Specification,Address,PhNo ;
Doctor D;
ofstream myfile;
myfile.open ("Doctor.txt",ios::app);
cout<<"please enter doctor ID: ";
cin>> DocID;
cout<<"please enter doctor Name: ";
cin>> Name;
cout<<"please enter doctor Department name: ";
cin>> Department;
cout<<"please enter doctor specification: ";
cin>> Specification;
cout<<"please enter doctor Address: ";
cin>> Address;
cout<<"please enter doctor Phone Number: ";
cin>> PhNo;
D.set_data(DocID,Name,Department,Specification,Address,PhNo);
myfile <<endl<<D.get_DocID()<<" "<<D.get_Name()<<" "<<D.get_Department()<<" "<<D.get_Specification()<<" "<<D.get_Address()<<" "<<D.get_PhNo();
myfile.close();
如何使用固定宽度的输入列生成对称的 .txt 文件
【问题讨论】:
-
如果 Doctor.txt 文件很长,那么读取其中的每个条目可能不是一个好习惯,重新格式化条目并再次写入。所以,如果我是你,我的主要问题不会是固定长度的条目。这将是“如果医生姓名中有空格怎么办?”因为您使用空格来分隔变量。这会导致混乱。
-
“使用基本数学”浮现在脑海中……尽管您可能还希望研究 I/O 操纵器。不过,jnbrq 有一点 - 如果您希望您的格式具有任何实际的实际用途,您可能应该呈现正确的、格式良好的 CSV。
-
@jnbrq-CanberkSönmez,如何处理空格?..我认为最好在条目之间引入“-”来代替空格。
-
您可以使用
。见this。它已经解决了您的问题。 -
@AwaisMahmood 有一些不可打印的字符,例如“\a”。任何类型的数据字段都可能不会给出这些字符。所以你可以考虑使用它们而不是空间。
标签: c++ fstream filehandle