How can I return a character string? To use it in main.

I have a variable: char item [20];

The user inputs the name of an item they wish to buy.
This is in the function int get_item()

How can I get it into main?

Using return won't work it gives me an error, but it does work for float and int variables!
Last edited on
If you use std::string instead of a char array, you can simply return the std::string.
Otherwise, pass in an array of chars to get_item and populate the array.
How do I use std::string?
1
2
3
4
5
6
7
#include <string>

int main()
{
std::string MyString;
MyString = "SomeText";
}
you can use strdup()
but it needs free after being used

for example:
char *get_item()
{
char item [20];
cin>>item;
return strdup(item);
}
int main()
{
char *item=get_item();
cout<<item<<endl;
free(item);
return 0;
}
Topic archived. No new replies allowed.