什么是现代当量(C ++)风格为老(C类)的fscanf方法? [英] What is the modern equivalent (C++) style for the older (C-like) fscanf method?

查看:106
本文介绍了什么是现代当量(C ++)风格为老(C类)的fscanf方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是最好的选择,如果我想升级老C- code到新的C ++读书用分号分隔符的文件时:

  / *从文件C类阅读:* /
的fscanf(tFile,%D,&安培; mypost.nr); / *分隔符; * /
的fscanf(tFile;%[^];,mypost.aftername); / *定界符; * /
的fscanf(tFile,%[^;],mypost.forename); / *分隔符; * /
的fscanf(tFile;%[^];,mypost.dept); / *定界符; * /
的fscanf(tFile,%[^];,mypost.position); / *定界符; * /
的fscanf(tFile,%D,&安培; mypost.nr2);// eqivalent最好的C ++实现的方法同样的事情?


解决方案

您可以在超载的的IStream右移位运算符的结构,所以:

 的std :: istream的&安培;运营商的GT;>(的std :: istream的&放大器是,mypost_struct&安培; MPS){
    是>> mps.nr;
    is.ignore(1,';');
    is.getline(mps.forename,255,';');
    is.getline(mps.aftername,255,';');
    是>> mps.dept;
    is.ignore(1,';');
    是>> mps.position;
    is.ignore(1,';');
    是>> mps.nr2;    回报;
}

随后,输入为简单的>> mypost; ,其中是你已经打开的文件

编辑:@UncleBens感谢指出了这一点,我忘了带空间帐户。我已经更新了答案,假设名字及aftername可能包含空格。还有是关于分隔符是双引号的这个相当embarrasing位...

我只是检查它使用的是结构定义为下:

 结构mypost_struct {
    INT NR;
    焦炭用的名字[255],aftername [255];
    INT部门,职位,NR;
};

..和结果符合市场预期。

What is the best option if I want to "upgrade" old C-code to newer C++ when reading a file with a semicolon delimiter:

/* 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?

解决方案

You could overload the right-shift operator on istream for your struct, so:

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;
}

Subsequently, input is as simple as is >> mypost;, where is is the file that you have opened.

Edit: @UncleBens Thanks for pointing this out, I had forgotten to take spaces in account. I have updated the answer, assuming that forename and aftername are likely to contain spaces. And there was this rather embarrasing bit about the delimiters being double-quoted...

I just checked it using a struct definition as under:

struct mypost_struct {
    int nr;
    char forename[255], aftername[255];
    int dept, position, nr2;
};

.. and the result was as expected.

这篇关于什么是现代当量(C ++)风格为老(C类)的fscanf方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆