我试图在二进制文件中写入和读取字符串,但我不明白为什么 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/