2013-04-08 105 views
0

爲什麼這裏的返回字符串上有各種垃圾?C++返回字符串不斷變垃圾

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困難得多。

回答

4

您需要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; 

替代地,離開數組大小相同,但使用,需要一個char *和字符數從源字符串讀取string constructor

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

謝謝,我會試一試。 – 2013-04-08 23:41:02