Is it possible to read infinity or NaN values using input streams?

后端 未结 6 1033
北荒
北荒 2021-01-01 08:45

I have some input to be read by a input filestream (for example):

-365.269511 -0.356123 -Inf 0.000000

When I use std::ifstream mystream;

6条回答
  •  攒了一身酷
    2021-01-01 09:06

    Although the question is quite old, I would like to contribute the solution that suited my purposes the most. If you consider using Boost, but Boost Spirit seems to be an overkill, you could try using the boost::math::nonfinite_num_put and boost::math::nonfinite_num_get locale facets 1 like this:

    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
      std::locale default_locale;
      std::locale tmp_locale(default_locale,
          new boost::math::nonfinite_num_put());
      std::locale upgraded_locale(default_locale,
          new boost::math::nonfinite_num_get());
    
      double inf = std::numeric_limits::infinity();
    
      std::stringstream out_s;
      out_s.imbue(upgraded_locale);
      out_s << inf;
      std::cout << out_s.str() << std::endl;
      std::stringstream in_s(out_s.str());
      in_s.imbue(upgraded_locale);
      double check_inf;
      in_s >> check_inf;
      std::cout << (inf == check_inf ? "nice" : "not nice") << std::endl;
      return 0;
    }
    

    Output:

    inf
    nice
    

提交回复
热议问题