2016-02-27 78 views
-1
#include <iostream> 
#include <string> 
#include <sstream> 

using namespace std; 

string swapLastName(const string full_name, const string new_last_name) 
{ 
string firstname; 
string newname; 

istringstream StrStream(full_name); 

// seperate first name from full name 
StrStream >> firstname; 

// combines first name with new last name 
newname=firstname +' '+ new_last_name; 

// outputs new name 
cout << "Your new name: " << newname << endl; 

} 

int main() 
{ 
string full_name; 
string new_last_name; 

//input full name 
cout << "Type your full name: "; 
//getline to get entire full name 
getline(cin, full_name); 
//input new last name 
cout << "Enter your new last name: "; 
getline(cin, new_last_name); 

swapLastName(full_name, new_last_name); 

return 0; 
} 

新的C++的種類,需要一些幫助,爲什麼我不斷收到分割錯誤(核心轉儲)錯誤。一切工作,他們我想要它,但運行後,我得到分段錯誤(核心轉儲)C++分割錯誤(核心轉儲)錯誤

+0

啓用您的編譯器警告。我很驚訝編譯器實際上可以用這個。 –

+0

這不會編譯。是否適合你?你永遠不會從swapLastName返回一個字符串 – NickLamp

+0

@NickLamp鏗鏘會顯然編譯這只是一個警告。那些混蛋。 –

回答

0

你不會從swapLastName返回任何東西,但你給它返回類型string。當控制到達函數末尾時,它不會返回string,所以它最後會以string大小的垃圾內存塊結束。 string析構函數在臨時被銷燬時運行,並且因爲所有內部字段都是未初始化的並且沒有意義,所以它可能會嘗試釋放一些隨機地址的段錯誤。