Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/qt/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ std::string缓冲区的奇怪行为_C++_Qt_Gcc_Std - Fatal编程技术网

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
缓冲区。