file - C++ return string keeps getting junk -


why return string here have 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 load of junk in string has junk on end of it, though debug says buffer being filled correct characters.

thanks, c++ lot harder java.

you need null terminate buffer. make buffer size 6 characters , 0 initialize it. fill first 5 locations you're doing now, leave last 1 alone.

char buffer[6] = {0};  // <-- 0 initializes array for(int x = 0; x < 5; x++){     buffer[x] = in.get();     cout << x << " " << buffer[x] << endl; } cout << buffer << endl; return buffer; 

alternately, leave array size same, use string constructor takes char * , number of characters read source string.

char buffer[5]; for(int x = 0; x < 5; x++){     buffer[x] = in.get();     cout << x << " " << buffer[x] << endl; } cout << buffer << endl; // still print out junk in case return string( buffer, 5 ); 

Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -