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

Mar 24, 2010 at 12:32am
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 Mar 24, 2010 at 12:43am
Mar 24, 2010 at 1:49am
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.
Mar 24, 2010 at 2:00am
How do I use std::string?
Mar 24, 2010 at 7:16am
1
2
3
4
5
6
7
#include <string>

int main()
{
std::string MyString;
MyString = "SomeText";
}
Mar 24, 2010 at 8:35am
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.