C++ 流ifilestream和使用cin获得一系列的字符?
所以我正在学习如何使用流来生成我自己类型的文件,我有一个简单的版本,它就是这样工作的C++ 流ifilestream和使用cin获得一系列的字符?,c++,stl,filesystems,filestream,C++,Stl,Filesystems,Filestream,所以我正在学习如何使用流来生成我自己类型的文件,我有一个简单的版本,它就是这样工作的 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;
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;
}
};
及
这可以正常工作,但我想用char doctorID[length]length=20或类似的值替换int doctorID,以存储医生名称,并使用空格和。例如,用户可以输入“Dr.Watson”或仅输入“Watson”
但是,当我使用cin获取信息时,它会因为空格或其他我不确定的原因而破坏代码。那么正确的方法是什么呢
第二个问题是,如果我想在用户输入字符[]时确定它的长度,该怎么办 要输入包含空格的字符串,请使用
cin.getline()
,它最多可读取一行新行:
char doctorID[20];
...
cout << "\nEnter a Doctor ID :" << endl;
cin.getline(appoint.doctorID, 20);
chardoctorid[20];
...
不能不要将结构重新解释为数据指针!这会将它绑定到当前编译器生成的内存中的任何表示形式。如果你改变了你的节目,你的流媒体就会中断
对于输出,第一步是在使用cin.getline(appoint.doctorID,20)时编写一个操作符;它只是移动到下一个cin,不允许我输入任何内容,将其留空?如果在格式化的cin操作(cin>>某物
)后执行cin.getline()
),则格式化操作的换行仍将在输入缓冲区中,cin.getline()
只读取该内容,而不是您的新行。调用cin.get();但是,您仍然使用固定缓冲区(本例中为100个字符),其缺点是:1)如果字符串远小于100个字符,则浪费空间;2)如果字符串大于100个字符(不太可能,但可能),则运气不佳。因此,我仍然建议您使用std::string
。[由于字符限制,在下一个注释中继续]如果您使用std::string
(从
标题),您将使用getline(cin,s)
读取输入字符串,其中s
是std::string
变量。字符串将自动调整为所需的长度,您可以调用size()
获取其长度。只要先将字符串的长度写入文件,然后再读取,这样您就可以知道要读取多少个字符,是的,您可以使用字符数组或std::string
。这就是我在说选项2“编写自己的函数将字符串序列化/反序列化为二进制文件”时想到的。只是要小心,因为这类代码可能很难正确使用。我想使用二进制表示。因为我正在制作我自己的文件格式,并打开/写入/修改我没有制作的其他二进制格式。然后在二进制模式下打开您的ofstream<流myfile的代码>;myfile.open(“example.bin”,ios::out | ios::binary)代码>也许这会更清楚地说明问题:如何保证编译器在每次编译时都以完全相同的方式在内存中布局结构?如果您希望获得此保证,则需要向编译器提供比当前更多的信息。
ofstream ofilestream( fileName.c_str(), std::ios_base::out | std::ios::binary );
Appointment appoint = Appointment::GetDataFromUser();
ofilestream.write((char *)&appoint, sizeof(Appointment));
char doctorID[20];
...
cout << "\nEnter a Doctor ID :" << endl;
cin.getline(appoint.doctorID, 20);
struct Appointment
{
// previous contents
friend ostream& operator<<(ostream& out, Appointment const& app);
};
ostream& operator<<(ostream& out, Appointment const& app)
{
out << app.doctorID << std::endl;
// out << app.OtherField for each field
return out;
}