2016-02-27 77 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析构函数在临时被销毁时运行,并且因为所有内部字段都是未初始化的并且没有意义,所以它可能会尝试释放一些随机地址的段错误。