Correct use of string::copy?

Jun 8, 2015 at 12:59pm
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;
}
Jun 8, 2015 at 1:47pm
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.

Jun 8, 2015 at 2:00pm
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 Jun 8, 2015 at 2:02pm
Topic archived. No new replies allowed.