如果我想在读取带有分号分隔符的文件时将旧的 C 代码“升级”到更新的 C++,最好的选择是什么:
/* reading in from file C-like: */
fscanf(tFile, "%d", &mypost.nr); /*delimiter ; */
fscanf(tFile, " ;%[^;];", mypost.aftername);/* delimiter ; */
fscanf(tFile, " %[^;]", mypost.forename); /*delimiter ; */
fscanf(tFile, " ;%[^;];", mypost.dept);/*delimiter ; */
fscanf(tFile, " %[^;];", mypost.position);/* delimiter ; */
fscanf(tFile, "%d", &mypost.nr2);
//eqivalent best C++ method achieving the same thing?
最佳答案
您可以为您的结构重载 istream 上的右移运算符,因此:
std::istream& operator>>(std::istream& is, mypost_struct& mps) {
is >> mps.nr;
is.ignore(1, ';');
is.getline(mps.forename, 255, ';');
is.getline(mps.aftername, 255, ';');
is >> mps.dept;
is.ignore(1, ';');
is >> mps.position;
is.ignore(1, ';');
is >> mps.nr2;
return is;
}
随后,输入很简单,如is >> mypost;
,其中is
是你打开的文件。
编辑:@UncleBens 感谢您指出这一点,我忘记考虑空格了。我已经更新了答案,假设名字和名字后面可能包含空格。关于分隔符被双引号引起了相当尴尬的一点......
我刚刚使用如下结构定义检查了它:
struct mypost_struct {
int nr;
char forename[255], aftername[255];
int dept, position, nr2;
};
.. 结果如预期。
关于c++ - 旧的(类 C)fscanf 方法的现代等效(C++)样式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2537500/