I have a problem with the following code:
#include <iostream>
#include<cstring>
#include <stdio.h>
#include <string.h>
using namespace std;
char* email(char* nam, char* ln,char* dep,char* comp)
{
char str[260];
strcpy (str,nam);
strcat (str,ln);
strcat (str,"@");
strcat (str,dep);
strcat (str,".");
strcat (str,comp);
strcat (str,".com");
return str;
}
int main()
{
cout << "Hello world!" << endl;
char nam[50], ln[80], comp[100], dep[30];
char* e_mail = 0;
cout << "Name: ";
cin >> nam;
cout << "Last name: ";
cin >> ln;
cout << "company: ";
cin >> comp;
cout << "Which department: ";
cin >> dep;
e_mail = email(nam,ln,dep,comp);
cout << "email: " << e_mail << "\n has length: " << strlen(e_mail) << "\n";
return 0;
}
All of these lines above should make an email adress, meanwhile it prints this:
I tried to do this with cout at the end of email function but it spoils the end result and doesn't print it correctly.
std::stringin C++?stronly exists within the function and is destroyed when the function returns. Therefore the pointer tostrwhich the function is returned becomes invalid.