Correct use of string::copy?

I'm getting a weird error when I run this. "testCopy" should equal "test" which equals to "hello". What's wrong with my copy function?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>
using namespace std;

int main() 
{
	string test = "hello";
	string testCopy;

	testCopy = test.copy(test, 5, 1);

	cout << endl << testCopy << endl;

	return 0;
}
Since you're using two strings you really should use the substr() function instead of the copy() function. The copy() function copies the substring into the first parameter and returns the number of characters copied.

By the way that first parameter should be a pointer to an array of char not a string.

1) The stream::copy return a size_t value;
2) You just copy the string to itself;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>
using namespace std;

int main() 
{
	string test = "hello";
	char testCopy[6];

	test.copy(testCopy, 5, 0);

	cout << "testCopy:"<< testCopy << endl;

	return 0;
}
Last edited on
Topic archived. No new replies allowed.