为什么这里的返回字符串上有各种垃圾?
string getChunk(ifstream &in){
char buffer[5];
for(int x = 0; x < 5; x++){
buffer[x] = in.get();
cout << x << " " << buffer[x] << endl;
}
cout << buffer << endl;
return buffer;
}
ifstream openFile;
openFile.open ("Bacon.txt");
chunk = getChunk(openFile);
cout << chunk;
即使我的调试表明我的缓冲区正在填充正确的字符,我也会在字符串中收到大量垃圾,其中末尾有垃圾。
谢谢,c++比Java难多了。
您需要 NULL 终止缓冲区。将缓冲区大小设置为 6 个字符并对其进行零初始化。像现在一样只填充前 5 个位置,保留最后一个位置。
char buffer[6] = {0}; // <-- Zero initializes the array
for(int x = 0; x < 5; x++){
buffer[x] = in.get();
cout << x << " " << buffer[x] << endl;
}
cout << buffer << endl;
return buffer;
或者,保持数组大小相同,但使用字符串构造函数 http://en.cppreference.com/w/cpp/string/basic_string/basic_string这需要一个char *
以及从源字符串中读取的字符数。
char buffer[5];
for(int x = 0; x < 5; x++){
buffer[x] = in.get();
cout << x << " " << buffer[x] << endl;
}
cout << buffer << endl; // This will still print out junk in this case
return string( buffer, 5 );
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)