c++ - 旧的(类 C)fscanf 方法的现代等效(C++)样式是什么?

标签 c++ c scanf

如果我想在读取带有分号分隔符的文件时将旧的 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/

相关文章:

c++ - 在 Linux 运行时重定向 FIFO

c - Mac OSX Lion 上的 MongoDB C 驱动程序

计算导数,给定数据文件

c++ - unordered_map::find() 插入查找的键

c++ - 赋值运算符的奇怪行为

c++ - 在 C++ (Windows) 中选择录音设备

php - 升级流程繁重的 PHP 和 MySQL 应用程序的语言建议

c - 如何让 Makefile 将 obj 文件放在单独的目录中?

c - 用C读取格式化数据

c - scanf 循环和信号处理程序