C++字符串到C char数组以写入二进制文件

标签 c++ arrays string

我试图在二进制文件中写入和读取字符串,但我不明白为什么 sizeof(t) 返回 4。

//write to file
ofstream f1("example.bin", ios::binary | ios::out);
string s = "Valentin";
char* t = new char[s.length()+1];
strcpy(t, s.c_str());
cout << s.length()+1 << " " << sizeof(t) << endl; // prints 9 4
for(int i = 0; i < sizeof(t); i++)
{
    //t[i] += 100;
}
f1.write(t, sizeof(t));
f1.close();

// read from file
ifstream f2("example.bin", ios::binary | ios::in);
while(f2)
{
    int8_t x;
    f2.read((char*)&x, 1);
    //x -= 100;
    cout << x;  //print Valee
}
cout << endl;
f2.close();

无论我在 char* 数组 t 中放入什么大小,代码总是打印“4”作为它的大小。要写入超过 4 个字节的数据,我必须做什么?

最佳答案

下面是如何以简单的方式编写代码

//write to file
ofstream f1("example.bin", ios::binary | ios::out);
string s = "Valentin";
f1.write(s.c_str(), s.size() + 1);
f1.close();

编辑 OP 实际上想要这样的东西

#include <algorithm> // for transform

string s = "Valentin";
// copy s to t and add 100 to all bytes in t
string t = s;
transform(t.begin(), t.end(), t.begin(), [](char c) { return c + 100; });
// write to file
ofstream f1("example.bin", ios::binary | ios::out);
f1.write(t.c_str(), t.size() + 1);
f1.close();

关于C++字符串到C char数组以写入二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55104214/

相关文章:

c++ - 表示硬件设备的适当类结构

c++ - -Wreorder 和构造函数初始化列表

c - 打印数组的最快格式

php - 降序排列

Java 8 : Why can't I parse this binary string into a long?

c# - 如何通过正则表达式检查允许 '[' 和 ']'

java - 如何检索字符串中匹配模式的索引?

c++ - 在 C++ 控制台应用程序中运行两个线程

c++ - 这种类型到底是什么?

java - 来自 leetcode 的 Java 中的两个和