473,465 Members | 1,489 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

function returning a string?

Hi,
how to write a function that would return a string?
I've tried something like this:

char enterstring(void)
{
char somestring[15];
printf("\tstring: ");
fgets(somestring, sizeof somestring, stdin);
return somestring;
};

but it doesn't work :(

Jan 4 '06 #1
8 22099
alternativa <al***********@wp.pl> wrote:
how to write a function that would return a string?
You either need to pass it a place to store the string you want to
return or malloc() space on your own, keeping in mind that it is the
caller's responsibility to see that the returned string is free()'d
properly.
I've tried something like this: char enterstring(void)
somestring is a character array, not a char. If you want to return a
string, return char *.
{
char somestring[15];
printf("\tstring: ");
IIRC, without a newline here, you are not guaranteed to see this
string before you are expected to enter a string. fflush() would
probably be helpful.
fgets(somestring, sizeof somestring, stdin);
At least you didn't use gets(). Good.
return somestring;
Completely wrong. The space associated with somestring will be gone
and inaccessable after the function returns.
};


#define MAX_STRING 128

char * enterstring( void )
{
char *ret=malloc( MAX_STRING );
if( !ret ) {
/* Error */
return ret;
}
fgets( ret, MAX_STRING, stdin );
return ret; /* Caller is responsible for free()'ing this pointer */
}

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
Jan 4 '06 #2
M.B

alternativa wrote:
Hi,
how to write a function that would return a string?
I've tried something like this:

char enterstring(void)
{
char somestring[15];
printf("\tstring: ");
fgets(somestring, sizeof somestring, stdin);
return somestring;
};

but it doesn't work :(


char *enterstring(void) /* note return typw is char *
not char*/
{
static char somestring[15]; /u cannot return ptr to a auto
local var so use static */
printf("\tstring: ");
fgets(somestring, sizeof somestring, stdin);
return somestring;
} /* u dont put ';' after
function brace */
take care to use strcpy for persistant use of string
ex int main(void) { char a[20]; strcpy(a,enterstring()); ...}

better is to pass argument of enterstring as a char *
ex:
void enterstring(char *str,int len /*to take care of max length*/)

Jan 4 '06 #3
thanks a lot, now I have a new problem.. I wish to pass this string to
a field of a structure.
For other fields - containing numbers - I used something like this:

somenumber = enternumber ();
currp->num1 = sumenumber;

where currp->num1 is a pointer to a structure's field called 'num1'.

Unfortunately in the case of string I cannot compile and the message
is: incompatibile types in assignment. I guess I should now include the
fact that I use pointers, but everything I've tried conclued with a
message "pointer from integer without a cast".
I know I'm one of those annoying newbies ;), but please safe my life..
I have no idea how to solve this problem :(

Jan 4 '06 #4

alternativa wrote:
thanks a lot, now I have a new problem.. I wish to pass this string to
a field of a structure.
For other fields - containing numbers - I used something like this:

somenumber = enternumber ();
currp->num1 = sumenumber;

where currp->num1 is a pointer to a structure's field called 'num1'.

Unfortunately in the case of string I cannot compile and the message
is: incompatibile types in assignment. I guess I should now include the
fact that I use pointers, but everything I've tried conclued with a
message "pointer from integer without a cast".
I know I'm one of those annoying newbies ;), but please safe my life..
I have no idea how to solve this problem :(


Hi Alternativa,

It sounds like you just have a string / number confusion. I think you
are trying to get a user to input a number which you read from the
command line (or whereever) as a string e.g. "52". Then you want to
store "52" as a number 52.

So a good way around this is to NOT return a string pointer (char *),
but to instead convert it to a number first and then return and
integeter.

Or alternativly convert after the function. BUT you cannot just assign
an integer to a char value and expect to get a valid result!

Can of course cast the (char *) to an integer if you want to "force"
the issue, but this will not give you the result you want (e.g.
my_int = (int) my_char_ptr;)

Alastair

Jan 4 '06 #5
alternativa wrote:

thanks a lot, now I have a new problem.. I wish to pass this
string to a field of a structure. For other fields - containing
numbers - I used something like this:


Consider using my ggets function to input the string. Available
at: <http://cbfalconer.home.att.net/download/ggets.zip>

Then you can:

struct thing {
....
char *wantedstring;
....
} thething;

.....

if (0 != ggets(&thething.wantedstring)) failure();
else {
donesocarryon();
}

or, if you need to access some file f other than stdin:

if (0 != fggets(&thething.wantedstring, f)) failure();
else {
donesocarryon();
}

Note that you pass ggets the address of a pointer to char. When
done with it don't abandon it, you should free it:

free(thething.wantedstring);
thething.wantedstring = NULL;

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell.org/google/>
Jan 4 '06 #6
alternativa wrote:
Hi,
how to write a function that would return a string [that the user inputs]?


Try looking here:

http://cbfalconer.home.att.net/download/index.htm
http://cbfalconer.home.att.net/download/ggets.zip

Good luck.

Rob Adams
Jan 4 '06 #7
M.B

alternativa wrote:
thanks a lot, now I have a new problem.. I wish to pass this string to
a field of a structure.
For other fields - containing numbers - I used something like this:

somenumber = enternumber ();
currp->num1 = sumenumber;

where currp->num1 is a pointer to a structure's field called 'num1'.

Unfortunately in the case of string I cannot compile and the message
is: incompatibile types in assignment. I guess I should now include the
fact that I use pointers, but everything I've tried conclued with a
message "pointer from integer without a cast".
I know I'm one of those annoying newbies ;), but please safe my life..
I have no idea how to solve this problem :(


Furst of all I do not know the declaration of function "enternumber ()"
I guess it is like (from past mails also)

char *enternumber(void)

And structure definition is like
struct xyz {
int *num1; /* why the hell is this a pointer, i dont understand
*/
...
};

Your code may be
struct xyz *currp=calloc(...);
currp0>num1=calloc(...); /* this is needed if num1 is int * */

then *(currp->num1)=atoi(enternumber());
should work fine if @stdlib.h is included
-
M.B

Jan 5 '06 #8
"alternativa" <al***********@wp.pl> writes:
how to write a function that would return a string?
I've tried something like this:

char enterstring(void)
{
char somestring[15];
printf("\tstring: ");
fgets(somestring, sizeof somestring, stdin);
return somestring;
};

but it doesn't work :(


The C FAQ is at <http://www.c-faq.com>. See questions 7.5a and 7.5b.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jan 5 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: Derek Hart | last post by:
I wish to execute code from a string. The string will have a function name, which will return a string: Dim a as string a = "MyFunctionName(param1, param2)" I have seen a ton of people...
5
by: shyam | last post by:
Hi All I have to write a function which basically takes in a string and returns an unknown number( at compile time) of strings i hav the following syntax in mind char *tokenize(char *) ...
2
by: Tany | last post by:
How can I declare function returning array of Integer pointers . Please help !!
17
by: I.M. !Knuth | last post by:
Hi. I'm more-or-less a C newbie. I thought I had pointers under control until I started goofing around with this: ...
14
by: Fabian Steiner | last post by:
Hello! I have got a Python "Device" Object which has got a attribute (list) called children which my contain several other "Device" objects. I implemented it this way in order to achieve a kind...
18
by: svata | last post by:
Hello to all, as a result from my previous post I'm busy with splitting code into functions. The one problem ( out of many ) I encounter is how to properly use/code a function which returns...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.