这个程序有什么问题吗?
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string x;
getline(cin,x);
ofstream o("f:/demo.txt");
o.write( (char*)&x , sizeof(x) );
}
我得到了意外的输出。我没有得到我在字符串函数中编写的内容。 这是为什么? 请解释一下。
就像我在文件中编写 steve pro
时得到的输出为 8/ steve pro ÌÌÌÌÌÌ ÌÌÌÌ
我希望输出为 史蒂夫·普罗
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string x;
getline(cin,x);
ofstream o("f:/demo.txt");
o.write( (char*)&x , sizeof(x) );
}
I get the unexpected output.I don't get what i write in a string function.
Why is this ?
Please explain .
Like when i write steve pro
i get the output as 8/ steve pro ÌÌÌÌÌÌ ÌÌÌÌ
in the file
I expect that the output be steve pro
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您正在将
std::string
视为某种东西,但事实并非如此。它是一个复杂的对象,在其内部的某个地方为您存储字符。没有理由假设字符数组位于对象的开头 (
&x
),并且对象的sizeof
与它有多少个字符无关可能间接持有/代表。您可能正在寻找:
或者只是使用内置格式化 I/O 机制:
You are treating an
std::string
like something that it is not. It's a complex object that, somewhere in its internals, stores characters for you.There is no reason to assume that a character array is at the start of the object (
&x
), and thesizeof
the object has no relation to how many characters it may indirectly hold/represent.You're probably looking for:
Or just use the built-in formatted I/O mechanism:
您的
sizeof
模型似乎不正确,所以让我尝试使其正确。对于任何给定的
T
类型的对象x
,表达式sizeof(x)
是一个编译时常量。 C++ 永远不会在运行时实际检查对象x
。编译器知道x
是T
类型,因此您可以想象它默默地将sizeof(x)
转换为sizeof(T)
,如果你愿意的话。所有相同类型的 C++ 对象占用的内存量完全相同。当然,由于字符串的长度差异很大,因此它们将在内部存储指向堆分配的内存块的指针。但这与
sizeof
无关。它不能,因为正如我所说,sizeof
在编译时运行。You seem to have an incorrect model of
sizeof
, so let me try to get it right.For any given object
x
of typeT
, the expressionsizeof(x)
is a compile-time constant. C++ will never actually inspect the objectx
at runtime. The compiler knows thatx
is of typeT
, so you can imagine it silently transformingsizeof(x)
tosizeof(T)
, if you will.All C++ objects of the same type take up the exact amount of memory. Of course, since strings have vastly different lengths, they will internally store a pointer to a heap-allocated block of memory. But this does not concern
sizeof
. It couldn't, because as I said,sizeof
operates at compile-time.你得到的正是你所写的内容:指向 char 的指针的二进制原始值...
如果你坚持直接写入缓冲区,你可以使用
PS 对代码格式的一点关注可以让你头脑清醒
You get exactly what you write: the binary raw value of a pointer to char...
If you insist on writing a buffer directly, you can use
PS A little attention to code formatting unclouds the mind
您正在传递对象的地址以写入文件,而原始内容位于其他地方,由其内部指针之一指向。
试试这个:
You're passing the object's address to write into the file, whereas the original content lies somewhere else, pointed to by one of its internal pointers.
Try this: