在c++中保存Int数据到文本文件
Save Int Data into Text File in C++
我正在将数据保存到文本文件中并将其与另一个文本文件进行比较。下面是我编写的代码:
ofstream outfile;
outfile.open("Data",ios::out | ios :: binary);
for(x=0; x<100; x++)
{
printf("data- %xn", *(((int*)pImagePool)+x));
int data = *(((int*)pImagePool)+x);
//outfile<<(reinterpret_cast<int *>(data))<<endl;
outfile<<(int *)data<<endl;
}
从printf
读取的结果是24011800
,从文本文件读取的结果是0x24011800
为什么会出现0x
?我们能把它取出来吗?
reinterpret_cast<int *> & (int *)
之间的区别是什么,但两者都给出了相同的结果?
这是因为您将其强制转换为指针,因此输出将是指针。
由于data
是一个正常的值变量,就像往常一样写:
outfile << data << 'n';
我还建议你在编程c++时停止使用printf
,没有理由使用它。使用std::cout
:
std::cout << "data- " << *(((int*)pImagePool)+x) << 'n';
或者如果你想要十六进制输出
std::cout << "data- " << std::hex << *(((int*)pImagePool)+x) << 'n';
"%x"是十六进制数的说明符。检查此表:http://www.cplusplus.com/reference/cstdio/printf/
使用"%d"输出小数。
编辑:关于选角,请参阅:
Reinterpret_cast与c风格的强制转换
这是一个使用ofstream函数的非常简单的例子。最复杂的部分是传递给open的参数,特别是std::ios::out,它指定了文件的方向。您还可以使用std::ios:in和cin一起从文件中读取。
// ex5.cpp
#include <string>
#include <iostream>
#include <fstream>
#include "hr_time.hpp"
#include >ios>
int main(int argc, char * argv[])
{
CStopWatch sw;
sw.startTimer() ;
std::ofstream f;
f.open("test.txt",std::ios::out ) ;
for (int i=0;i<100000;i++)
{
f << "A very long string that is number " << i << std::endl;
}
f.close() ;
sw.stopTimer() ;
std::cout << "This took " << sw.getElapsedTime() << " seconds" << std::endl;
return 0;
}
相关文章:
- 文本文件中的单词链表
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 如何将内容数组写入文本文件?
- 无法通过空白将文本文件行分隔为矢量
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- C++将文本文件中的数据读取到结构数组中
- 在指针的帮助下,文本文件中单词的频率
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 将值从二维数组输出到文本文件
- 如何在c++中从文本文件中逐行读取整数
- 从文本文件中读取时钟时间和事件时间并进行处理
- 如何从文本文件中读取值和数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- C++试图读取一个文件并输出到另一个文本文件
- 如何通过套接字将文本文件的内容从服务器发送到客户端
- 已修改的LinkedList未在文本文件本身中更新
- C++文本文件的获取线
- 为什么C++的文件 I/O 在读取文本文件时忽略初始空行?我怎样才能让它不这样做?
- 打印逐行存储的文本文件
- C++文本文件输入