所以我正在学习如何使用流来制作我自己类型的文件,我有一个像这样工作的简单版本
struct Appointment
{
Appointment()
{
}
//
//and int to represent a certain doctor
int doctorID; // an enum to be made later
int year; // 1950 - 2050 100 years total
int month; // 0 - 11
int day; // 0 - 31
int hour; // 0 - 23
int minute; // 0 - 59
static Appointment GetDataFromUser()
{
Appointment appoint = Appointment();
cout << "\nEnter a Doctor ID :" << endl;
cin >> appoint.doctorID;
cout << "\nEnter a year 1900 - 3000 :" << endl;
cin >> appoint.year;
cout << "\nEnter a month 0 - 11 :" << endl;
cin >> appoint.month;
cout << "\nEnter a day of month 0 - 31 :" << endl;
cin >> appoint.day;
cout << "\nEnter an hour 0 - 23 :" << endl;
cin >> appoint.hour;
cout << "\nEnter an minute 0 - 59 :" << endl;
cin >> appoint.minute;
cout << "\nAll values entered thank you!" << endl;
return appoint;
}
};
然后在我使用的地方
ifstream ifilestream( fileName.c_str(), std::ios_base::in | std::ios::binary );
Appointment appoint;
ifilestream.read((char *)&appoint, sizeof(Appointment));
和
ofstream ofilestream( fileName.c_str(), std::ios_base::out | std::ios::binary );
Appointment appoint = Appointment::GetDataFromUser();
ofilestream.write((char *)&appoint, sizeof(Appointment));
这工作正常,但我想用 char doctorID[ length ] length might = 20 或其他值替换 int doctorID ,以用空格和 来存储医生姓名。例如,用户可以输入“Dr. Watson”或仅输入“Watson”。
但是当我这样做并使用 cin 来获取该信息时,它会破坏空格或其他我不确定的代码原因。那么正确的方法是什么?
第二个问题是,如果我希望 char[] 的长度在用户输入时确定怎么办?
最佳答案
要输入包含空格的字符串,请使用 cin.getline()
,它最多读取一个换行符:
char doctorID[20];
...
cout << "\nEnter a Doctor ID :" << endl;
cin.getline(appoint.doctorID, 20);
如果您想要一个大小在运行时确定的字符串,您应该使用 std::string
,它可以动态调整大小。
但是,如果您使用 std::string
,您将无法再像现在那样在文件中读取和写入结构。 (*) 您可以:
- 切换到基于文本的文件 格式
- 编写自己的函数
用于序列化/反序列化
std::string
到二进制文件 - 使用类似 Boost.Serialization 的序列化库
(*) 因为现在您只需按照内存中表示的方式编写结构;然而 std::string 的表示实际上只是指向另一个内存位置的指针
关于c++ - ofstream ifilestream 并使用 cin 获取字符数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6232741/