2016-08-08 102 views
0

我想打印使用MPFR的計算結果到文件,但我不知道如何。 MPFR用於高精度地進行浮點運算。要打印mpfr_t號所使用的功能:從MPFR打印到文件

size_t mpfr_out_str (FILE *stream, int base, size t n, mpfr t op, mp rnd t rnd)

我想我的問題是,我不明白FILE*對象以及它們如何與fstream對象。

如果我在mpfr_out_strstdout改變my_file然後爲我所希望的,但我不知道如何得到它到文件的數量將打印到屏幕上。

#include <mpfr.h> 
#include <iostream> 
#include <fstream> 
using namespace std; 
int main() { 
    mpfr_t x; 
    mpfr_init(x); 
    mpfr_set_d(x, 1, MPFR_RNDN); 

    ofstream my_file; 
    my_file.open("output.txt"); 
    mpfr_out_str(my_file, 2, 0, x, MPFR_RNDN); 
    my_file.close(); 
} 

回答

1

它可以使用與像mpfr_as_printf或mpfr_get_str MPFR功能的std :: ostream的方法。但是它需要額外的字符串分配。

#include <mpfr.h> 
    #include <iostream> 
    #include <fstream> 
    using namespace std; 
    int main() { 
    mpfr_t x; 
    mpfr_init(x); 
    mpfr_set_d(x, 1, MPFR_RNDN); 

    ofstream my_file; 
    my_file.open("output.txt"); 

    char* outString = NULL; 
    mpfr_asprintf(&outString, "%RNb", x); 
    my_file << outString; 
    mpfr_free_str(outString); 
    my_file.close(); 

    mpfr_clear(x); 
    } 
0

沒有太多的工作後,我發現這個更換底部4行代碼:

FILE* my_file; 
my_file = fopen("output.txt", "w"); 
mpfr_out_str(my_file, 2, 0, x, MPFR_RNDN); 
fclose(my_file);