then it works just fine. So "name" gets copied to "name2". If i try to cout << name2; (the whole thing) it doesn't work, but if i cout << name2[j]; (one by one in a loop) it works. It also works normally when i try to cout << name; Why is that?
Because you're trying to copy data to parts of memory that were never allocated to 'name2'. Just use the assignment operator ('=') without the square brackets and stop trying to treat std::string like it's the same as a cstring.
If pos is not greater than the string length, the function never throws exceptions (no-throw guarantee).
Otherwise, it causes undefined behavior.
The size of "name2" is 0, so everything you think write is undefined behaviour. The size does not change on line 16. It is pure misfortune that your second method to print appears to function.