我试图在二进制文件中读写字符串,但我不明白为什么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个字节的数据该怎么办?
答案 0 :(得分:3)
这是简单的编写代码的方法
//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();
答案 1 :(得分:2)
sizeof(char*)
打印指向一个或多个字符的指针使用的大小。在您的平台上是4。
如果需要字符串的大小,则应使用strlen
。或者,简单地,s.length()
。
答案 2 :(得分:2)
char *t
是一个指针,而不是数组,因此sizeof
将返回您计算机上指针的大小,显然是4个字节。
确定C样式字符串长度的正确方法是包含<cstring>
并使用std::strlen
。