You are on the right track. The only problem is that char is a single character, not a whole list of them (or array of them). You probably want to use a pointer to an array of chars.
Also, don't use %s in scanf() without qualifying it with a maximum width.
char *getString(char *string);
int main() {
char string[200];
getString(string);
}
char *getString(char *string) {
scanf("%200s",string);
return string;
}
You can pass the length of the target string into the function if you want:
char *getString( char *string, int length ) {
char format[ 30 ];
sprintf( format, "%%%ds", length );
scanf( format, string );
return string;
}
Hope this helps.
Duoas
Postaholic
2,043 posts since Oct 2007
Reputation Points: 1,140
Solved Threads: 229
Study the interface which fgets() provides.
Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
> Worked like a charm. Exactly what I needed.
That's a shame, considering that there's a bug in the code.
Let's see if other people can spot it.
Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
sorry, I should have said I changed it to this,
char *getString(char *string) {
scanf("%199s",string);
return string;
}
to provide for the null char. Thanks again:)
We still recommend:
char *getString(char *string) {
<strong>fgets(string, 200,stdio);</strong>
return string;
}
It's just too easy to make a mistake with scanf() . And why do you need to pull in the and execute the parsing for %d, %u, %i, %g, etc when fgets() requires nothing extra but reading a string. Safely.
WaltP
Posting Sage w/ dash of thyme
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
Yet still, the size of the buffer which is being written to isn't being passed as a parameter.
*shrug*
Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953