p3tter p3tter - 1 year ago 59
C++ Question

c++ return string or char from user input

im trying to return a string/char (tried with both) from a funtion:

char* foo(void)

{

using namespace std;
// char Name[100];
std::string Name;
std::cout << "Type your name : ";
//std::getline(std::cin, Name);
std::cin >> Name;

// std::cout << "Hello " << Name << "\n";

// std::string str(Name);
return Name;
}


which gives me this error:


/home/peter/netsend/main.cpp:22: error: cannot convert
'std::__cxx11::string {aka std::__cxx11::basic_string}' to
'char*' in return
return Name;
^


If i use char Name[100];
i get this warning when i compile my program:


/home/petter/netsend/main.cpp:13: warning: address of local variable
'Name' returned [-Wreturn-local-addr]
char Name[100];
^


when i run it i get:


ype your name : hh terminate called after throwing an instance of
'std::logic_error' what(): basic_string::_M_construct null not
valid Aborted (core dumped)


if i run this directly in int main it works:

using namespace std;
// char Name[100];
std::string Name;
std::cout << "Type your name : ";
//std::getline(std::cin, Name);
std::cin >> Name;

// std::cout << "Hello " << Name << "\n";

// std::string str(Name);


then i could use Name in my other functions in int main.
any ideas?

Thanks

Answer Source

Just return a string, like this:

auto foo()
    -> std::string
{
    using namespace std;
    string Name;
    cout << "Type your name : ";
    getline( cin, Name );
    return Name;
}

Or instead of the C++11 "trailing return type" syntax, use the old syntax

std::string foo()

… which means the same and is still much more common, but can't be used in every case.