unable to return string from function

Hi,

I have tried a program in which I wrote a function to get name from user and then I want to return that user name to main program.
When I execute it will ask to enter name but don't display it as per main program.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>

using namespace std;
class returnname
{
    char* name;
    public:
    char* get_name()
    {
        char name[10];
        cout<<"enter name :";
        cin>>name;
        char *y=name;  //here I am loosing my logic
        return y;
    }
};

int main()
{
   returnname rn;
   cout<<rn.get_name()<<endl;
   return 0;
}
The name array is a local variable inside the get_name function so as soon as the function ends the name array will no longer exist. That means the function returns a pointer to something that no longer exist and that is why you have problem printing it out on the screen.

The simplest solution is to use std::string from the <string> header instead of a char array.

1
2
3
4
5
6
7
string get_name()
{
	string name;
	cout<<"enter name :";
	cin>>name;
	return name;
}

closed account (48T7M4Gy)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>

class returnname
{
    private:
        char name[1000]; //<--
        
    public:
    char* get_name()
    {
        return name;
    }
    
    void set_name()
    {
        std::cout << "Enter name: ";
        std::cin >> name;
    }
};

int main()
{
   returnname rn;
   rn.set_name();
   std::cout << rn.get_name() << std::endl;
   return 0;
}

Enter name: C_plus_plus
C_plus_plus
Last edited on
std::string is safer. Using a character array risks buffer overflow. e.g. "C_plus_plus" requires 12 characters, 11 for the text plus 1 for the null terminator. One could guard against that by doing
 
    std::cin >> std::setw(10) >> name;
but overall the C++ std::string is easier to use as well as safer.
closed account (48T7M4Gy)
Exactly, that's the reason I did it that way! XDD
Last edited on
Topic archived. No new replies allowed.