Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Returning a char array from function

$
0
0
Hi!

I'm writing a program for my C++ class, and I'm trying to figure out how to return a character array as a string from a function.

I've been trying for a few hours now to figure this out. I know I cannot return an array, so I am trying to assign it to a string, and return the string. It is placing random junk in my string. (i.e. -e0)

I have to use gets and printf for I/O in this course, as per my instructor.

Here is my code:

string getName()
{
	char buffer[50];
	string name;

	printf("What is the name of this hauler?");

	gets(buffer);
	name = buffer;
	
	printf("%s", name);

	return name;

}


Please excuse the printf in the middle of the function, I am using it for testing (when I print print the buffer instead, it contains the correct hauler name).

This is beyond the scope of my program, so my professor said he doesn't have time to help me with it, which is understandable. I just REALLY want to figure this out, it seems like it shouldn't be so difficult. From what I have been reading in my research, it can be done, but I'm missing something. If i have to, I will iterate through the array and concat each letter onto the string separately, but there has to be a better way, right?

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>