在用vs2015编程学习文件流时出现问题,就是以二进制app方式写入和读取string类型时出现问题,只有第一次输入可以显示,之后增加字符串在此读取输出就会报错,求大神指点
以下是代码:
#include <string>
#include <iostream>
#include<iomanip>
#include<fstream>
using namespace std;
int main()
{
ofstream outfile("try.dat", ios::app | ios::binary);
string a;
cin >> a;
outfile.write((char*)&a, sizeof(a));
ifstream infile("try.dat", ios::in | ios::binary);
if (!infile)
{
cout << "weew";
}
infile.read((char*)&a, sizeof(a));
outfile.close();
infile.close();
cout << a << endl;
return 0;
}
以下是第一次运行情况,是正确的
接下来关闭后重新运行再次输入,会出现错误:
初学者不太明白这是为什么,第一次提问,求大神指点,先谢谢各位啦!
First of all, you must understand that
string
is not a simple array type, it is a class with its own member variables and member functionsAnd a is of type string, so a is a complex object. It doesn’t make sense to execute
&a
to get the address of a. It doesn’t make sense to force it to typechar*
. It doesn’t make sense to convert astring*
Forced conversion tochar*
is a pointer-to-pointer conversion. The value of the pointer has not changed . It just tells the compiler: It’s the same pointer. Don’t treat me like astring*
now. Now, think of me aschar*
(This is useful...)I feel that the original intention of the question is to convert a string into a traditional C string (that is, a char array), then please use
a.c_str()
to get the realchar*
(this is constructed internally by string, and It’s not randomly translated like the questioner did); in addition, you can usea.len()
to get the length of this string.By the way, if the questioner really can’t understand why
sizeof(a)
is not the length of the string , you can take a look at the following imitation example (created by me):You can see that
sizeof(a)
is alwayslen_string的长度
+str的长度
=8字节
and will not become 20 bytes. The so-called dynamic change of string length is throughnew
and a record Length variablelen_string
is implemented.1. The implementation of string is different in each library, but the same thing in the same library is that no matter how long the string is in your string, its sizeof() is fixed. The space occupied is dynamically allocated from the heap and has nothing to do with sizeof().
The second parameters of so, write and read are all wrong.
2. The second run error was when destructing string
3. If you change the buffer to receive it in read, there should be no data. You can try it. In other words, you The a read out is actually the original a
To obtain the C-style address of string, you need the c_str() member, and the length is string.len