C++ return string keeps getting junk

我与影子孤独终老i 提交于 2019-12-20 05:56:20

问题


Why does the return string here have all sorts of junk on it?

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;

I get a load of junk in the string where it has junk on the end of it, even though my debug says that my buffer is being filled with the correct characters.

Thanks, c++ is a lot harder than Java.


回答1:


You need to NULL terminate the buffer. Make the buffer size 6 characters and zero initialize it. Fill only the first 5 locations as you're doing now, leave the last one alone.

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;

Alternately, leave the array size the same, but use the string constructor that takes a char * and number of characters to read from the source string.

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 );


来源:https://stackoverflow.com/questions/15890891/c-return-string-keeps-getting-junk

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!