使用ifstream的作为的fscanf [英] Using ifstream as fscanf

查看:193
本文介绍了使用ifstream的作为的fscanf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个输入如下:

  N(X_1,Y_1)(X_2,Y_2)......(X_N,Y_N)

其中,N,X_i和Y_i都是整数。

一个例子:

  2(55,1)(521,7)

要读这一点,我可以做这样的事情(假设所有的变量定义等):

 的fscanf(翅,%D,&安培; N);
的for(int i = 0; I< N;我++)
   的fscanf(鳍(%D,%D),&安培; X [I],和放大器; Y [I]);

现在的问题是,我怎么能做到这一点很容易地使用ifstream的。我能得到的字符串的,然后我就可以摆脱非数字和使用字符串流,我可以得到两个数字,但是这似乎有点麻烦。是否有更简单,更优雅的方式?

感谢


解决方案

  INT N,X,Y;
焦炭℃;
如果(IS>> N)
    的for(int i = 0; I< N ++ I)
        如果(是与GT;&以及c&放大器;和C =='('和;&放大器;
            是>> X - 放大器;&安培;
            是>> C&功放;&安培; ç==','和;&安培;
            是>> Y'放大器;&安培;
            是>> C&功放;&安培; ç==')')
        {
            X [i] = X;
            Y [i] = Y;
        }
        其他
            抛出std :: runtime_error(无效输入);

您可以简化上述所有重要的内如果条件...

 是GT&;> chlit('(')GT;&X的催化剂>> chlit(,)GT;&GT y与其所连接;> chlit(')')

......与消费特定字符的简单支持类型:

 结构chlit
{
    chlit(CHAR C):C_(三){}
    焦炭C_;
};内联的std :: istream的&安培;运营商的GT;>(的std :: istream的&放大器是,chlit X)
{
    焦炭℃;
    如果(IS>> C&放大器;&安培;!C = x.c_)
        is.setstate(的std :: iostream的:: failbit);
    回报;
}

请参阅完整的方案说明这里上ideone这个

这是旧文章我的做的消耗特定字符串类似的东西。 (以上 chlit 可能是一个模板,但 chlit<','>()是丑陋的阅读和写 - 我宁愿相信编译器)

Assume that I have an input as follows:

N (X_1,Y_1) (X_2,Y_2) .... (X_N, Y_N)

where N, X_i and Y_i are integers.

An example:

2 (55,1) (521,7)

To read this, I can do something like this(assume all variables are defined, etc.):

fscanf(fin,"%d ",&N);
for (int i = 0; i < N; i++)
   fscanf(fin,"(%d,%d) ", &X[i], &Y[i]);

The question is, how can I do this easily using ifstream. I can get string's, and then I can get rid of nondigits and using stringstream I can get two numbers but this seems a bit cumbersome. Is there an easier, more elegant way?

Thanks

解决方案

int n, x, y;
char c;
if (is >> n)
    for (int i = 0; i < n; ++i)
        if (is >> c && c == '(' &&
            is >> x &&
            is >> c && c == ',' &&
            is >> y &&
            is >> c && c == ')')
        {
            X[i] = x;
            Y[i] = y;
        }
        else
            throw std::runtime_error("invalid inputs");

You can simplify the all-important inner if condition above to...

is >> chlit('(') >> x >> chlit(',') >> y >> chlit(')')

...with a simple support type for consuming a specific character:

struct chlit
{
    chlit(char c) : c_(c) { }
    char c_;
};

inline std::istream& operator>>(std::istream& is, chlit x)
{
    char c;
    if (is >> c && c != x.c_)
        is.setstate(std::iostream::failbit);
    return is;
}

See a complete program illustrating this on ideone here.

An old post of mine did something similar for consuming specific strings. (The above chlit could be a template, but chlit<','>() is ugly to read and write - I'd rather trust the compiler).

这篇关于使用ifstream的作为的fscanf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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