2011-06-03 80 views
8

下面的代码是写不可读的字符的文本文件:写入double类型值到一个文本文件

int main() 
{ 
    ofstream myfile ("example.txt"); 

    if (myfile.is_open()) 
    { 
     double value  = 11.23444556; 
     char *conversion = (char *)&value; 
     strcat (conversion, "\0"); 

     myfile.write (conversion, strlen (conversion)); 
     myfile.close(); 
    } 

    return 0; 
} 

我希望看到书面:(提示请在文件中的实际数量

EDIT 看到下面的答案,我修改的代码为:

int main() 
{ 
    ofstream myfile ("example.txt"); 

    if (myfile.is_open()) 
    { 
     double value  = 11.23444556; 

     myfile << value; 
     myfile.close(); 
    } 

    return 0; 
} 

这将产生putput:11.2344而实际数量是11.23444556。我想要完整的号码。

编辑后通知大家: 的不可读的字符是由于ofstream的的写功能:

这是一个未格式化输出功能

这句话是:http://www.cplusplus.com/reference/iostream/ostream/write/

+3

@Anisha - 默认是显示6位数字,如果你想要更高的精度,你可以使用'myfile << setprecision(10)<< value;'来获得数字的10位数。 – 2011-06-03 11:15:05

+2

@Bo Persson:要获得数字中的10位数字,'std :: fixed'也是必要的,否则后面的零不会被打印出来。 – Nawaz 2011-06-03 11:21:37

+1

在这种情况下抛出一个像这样的错误,除了错误之外,违反了严格的别名规则,所以你的代码无法工作。 – 2011-06-03 12:35:29

回答

18

你为什么不简单地做这个(在问题编辑后更新的答案):

myfile << std::fixed << std::setprecision(8) << value; 
myfile.close(); 

现在,您可以看到写入文件的实际数字。

请参阅std::setprecision的文档。注意:您对包括<iomanip>头文件,看看它是如何工作的:http://www.ideone.com/XNZjK

+0

看到上面的编辑。谢谢 – 2011-06-03 11:10:05

+1

@Anisha:现在就看。我更新了它。使用'std :: fixed'和'std :: setprecision(8)' – Nawaz 2011-06-03 11:13:07

+1

谢谢,现在它工作得非常出色!你能分辨出原来的代码有什么问题吗? – 2011-06-03 11:17:38

3

它很容易在这里使用流运营商:

#include <iostream> 
#include <fstream> 
#include <string.h> 
using namespace std; 

int main() 
{ 
    ofstream myfile ("example.txt"); 

    if (myfile.is_open()) 
    { 
     double value  = 11.23444556; 

     myfile << value; 
     myfile.close(); 
    } 

    return 0; 
} 

给你想要的东西。

0

可以写入文件中像这样的值:

myfile << value; 

使用的值ADRESS作为参数strcat破坏你的筹码,因为strcat需要一个0结尾的C字符串作为第一个参数(和实际分配空间)。

0

其他建议更好的方法,但如果你真的想这样做的指针方式应该有管型转换的char *加倍*反之亦然

#include <iostream> 
#include <fstream> 
#include <string> 
#include <cstring> 
using namespace std; 

int main() 
{ 
    ofstream myfile ("example.txt"); 
    if (myfile.is_open()) 
    { 
    double value  = 11.23444556; 
    char  *conversion = reinterpret_cast<char *>(&value); 
    strcat (conversion, "\0"); 
    //myfile.write (*conversion, strlen (conversion)); 
    myfile << *(reinterpret_cast<double *>(conversion)); 
    myfile.close(); 
    } 
    return 0; 
}