C++ std::string缓冲区的奇怪行为
我发现C++ std::string缓冲区的奇怪行为,c++,qt,gcc,std,C++,Qt,Gcc,Std,我发现std::string 我编译了下面的代码并在ubuntu上执行,我得到了不同的char buffer和std::stringbuffer输出 string m_fileName = "test.txt"; ifstream myfile; myfile.open (m_fileName.c_str(), ios::out | ios::app | ios::binary); string readBuffer=""; string fileContent = ""; char data
std::string
我编译了下面的代码并在ubuntu上执行,我得到了不同的char buffer和std::string
buffer输出
string m_fileName = "test.txt";
ifstream myfile;
myfile.open (m_fileName.c_str(), ios::out | ios::app | ios::binary);
string readBuffer="";
string fileContent = "";
char data[2048];
strcpy(data,"");
while(myfile.read((char *)readBuffer.c_str(),13)) {
strcat(data,readBuffer.c_str());
fileContent += readBuffer;
}
myfile.close();
QMessageBox msgBox;
msgBox.setText(fileContent.c_str());
msgBox.exec();
QMessageBox msgBox1;
msgBox1.setText(data);
msgBox1.exec();
std::string
fileContent仅显示最后一行。
字符数据显示整个文件内容。
??您正在写入未分配的内存。这是未定义的行为,任何事情都可能发生。您需要更改代码的某些行,如下所示:
string m_fileName = "test.txt";
ifstream myfile;
myfile.open (m_fileName.c_str(), ios::out | ios::app | ios::binary);
char readBuffer[24];
string fileContent = "";
char data[2048];
strcpy(data,"");
while(myfile.read(readBuffer,13)) {
strcat(data,readBuffer);
fileContent.append(readBuffer);
fileContent += readBuffer;
}
myfile.close();
是否打开的myfile带有附加输出的标志?当你不知道
.c_str()
上有13个字符可供你使用时,请读入readBuffer
——真是一团糟!在谷歌上搜索“C++将文件读入字符串”,你会看到很多例子。(char*)readBuffer.C_str()
那东西之所以是const
,是有原因的。铸造不是什么银弹。和次,数据[0]=0代码>足以设置终止的缓冲区。不需要那种strcpy()
这真的可以用一两段话来描述为什么需要改变东西;它完全忽略std::string
缓冲区。