Hey everyone,

I'm working on function that will take in a char array, prompt the user to input a string, and then return that string to the function. Below is what I've been working on and yes, I know it is not the right syntax, but I'm hoping someone could help me fix it so it works. Thanks!

-Barefoot

char getString(char)

int main() {
    char string[200];
    string = getString(string);
}

char getString(char string) {
    scanf("%s",string);
    return string;
}

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.

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;
}

Ahh, thanks. Worked like a charm. Exactly what I needed.

> 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.

> 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.

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:)

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) {
	[B]fgets(string, 200,stdio);[/B]
	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.

Yet still, the size of the buffer which is being written to isn't being passed as a parameter.
*shrug*

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.