我试图写入和从二进制文件读取字符串,但我不明白为什么sizeof(t)返回4。
//写入文件ofstream f1(“example.bin”,ios :: binary | ios :: out);string s =“Valentin”;…
以下是如何以简单的方式编写代码
//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();
sizeof(char*) 将指针使用的大小打印到(a)char(s)。它在你的平台上是4。
sizeof(char*)
如果你需要字符串的大小,你应该使用 strlen 。或者,简单地说, s.length() 。
strlen
s.length()
char *t 是一个指针,而不是一个数组,所以 sizeof 将返回机器上指针的大小,显然是4个字节。
char *t
sizeof
确定C风格字符串长度的正确方法是包括 <cstring> 并使用 std::strlen 。
<cstring>
std::strlen