C++ return string keeps getting junk

2019-03-03 17:09发布

问题:

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


标签: c++ file buffer