这个程序有什么问题? [英] what is wrong with this program?
问题描述
#include< iostream>
#include< string>
#include< fstream>使用namespace std
;
int main(){
string x;
getline(cin,x);
ofstream o(f:/demo.txt);
o.write((char *)& x,sizeof(x));
}
我得到了意想不到的输出。我不知道我写的是什么字符串函数。
这是为什么?
请解释。
就像当我写 steve pro
我得到输出为 8 /文件中的
我希望输出史蒂夫亲
您正在处理 std :: string
喜欢它不是的东西。它是一个复杂的对象,在其内部的某个地方为你存储字符。
没有理由假设字符数组位于对象的开头(& x
), sizeof
该对象与它间接保持/代表的字符数无关。 / p>
您可能正在寻找:
o.write(x .c_str(),x.length());
或者只使用内置的格式化I / O机制:
o<< X;
#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
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 the sizeof
the object has no relation to how many characters it may indirectly hold/represent.
You're probably looking for:
o.write(x.c_str(), x.length());
Or just use the built-in formatted I/O mechanism:
o << x;
这篇关于这个程序有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!