what I get back in my string (in this case in sStr) is giberish |
No, sStr will point to the empty string, just like before the call.
I did something similar to the above example, but what I get back in my string (in this case in sStr) is giberish, since (i think) after the function closes it lets go of all the memory it had, so therefor all the allocated memory, and hence the data it stored in the string *, is this the case? |
Heavens, no. You need to explicitly delete the objects with delete[]. As it is now, you have a bad memory leak.
This doesn't work because you're assigning the return value of new[] to a local pointer, which will be destroyed when the function exits (just the pointer, not the memory it points to!) and the allocated memory will be unreachable.
If you pass by reference, sWord in funct will be an alias for the pointer in main.
Still, messing around with new[] and delete[] is a bad idea.
An acceptable way to do this is to pass a string vector that the function can write the contents to:
1 2 3 4 5 6
|
void readFile(vector<string>& lines)
{
fstream file("text.txt");
string line;
while (getline(file, line))lines.push_back(line);
}
|
or alternatively (if you know your compiler can apply RVO here):
1 2 3 4 5 6 7 8
|
vector<string> readFile()
{
vector<string> lines;
fstream file("text.txt");
string line;
while (getline(file, line))lines.push_back(line);
return lines;
}
|