std::copy kind of not working

Hi, I tried to copy array of chars into string but for some reason it didn't work
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
#include <algorithm>
#include <cstring>

int main()
{
  const char* text= "Example text";
  std::string str;
  unsigned int text_lenght = std::strlen(text);
  
  str.reserve(text_lenght);
  std::copy(&text[0], &text[0] + text_lenght, str.begin());  //whats wrong with this line?
  
  std::cout << " copied string = " << str << std::endl;
  
  return 0;
}

output :
copied string = 


Later on I found that I can simply use std::string str(text); and it works fine and I should probably use it. But I cant seem to understand why the previous code didn't work. Any ideas?
Last edited on
You can't use any of the std::copy on C strings (char *).
Actually it's not the std::copy line that is the problem, it is the str.reserve() line that is the problem. The reserve() method only increases the capacity of the string it doesn't actually change the size of the string. You need to use resize() instead.
1
2
 str.resize(text_lenght);
  std::copy(text, text + text_lenght, str.begin()); 


Also you don't really need the &text[0], all you really need is the name.
Last edited on
@koothkeeper,

you can use stl algorithms with "normal" arrays.
The algorithms need iterators and in many cases a pointer can be used as an iterator. I am not sure if there are exceptions.
Ohh man! Tnx a lot guys for you help :)
@Thomas1965: Thanks! I learn something new every day.
Or you can use an insert iterator
1
2
3
4
5
6
	str.reserve(text_length);
	std::copy(
		text,
		text+text_length,
		std::back_inserter(str)
	);
the iterator would call `.pushback()' on the container, so don't have to `.resize()'
( `.reserve()' would be only an optimization to avoid reallocation, but can be omited)
Cool man. First time I actually see something like this. Much appreciated :)
Topic archived. No new replies allowed.