copy first n letters of string

Hello,

I am attempting to copy the first n letters of a string into another, and the output is not what I expected based on the constructor.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>

int main() {
std::string str1("Hello World");

std::string str2(str1, 5);

std::cout << str2 << endl; 

return 0;

} 

The output should be: Hello

Actual output:
World


If I am reading the reference right, I believe the assignment should be done from the beginning of the array, not the end.


Any assistance or directions to better references would be appreciated.

T.

If I am reading the reference right

Well...
Reference wrote:
string ( const string& str, size_t pos, size_t n = npos );
Content is initialized to a copy of a substring of str. The substring is the portion of str that begins at the character position pos and takes up to n characters (it takes less than n if the end of str is reached before).
You want: std::string str2(str1, 0, 5); //starting at 0, with a length of 5
That worked great! Thanks for the quick feedback. I double checked my book and it definitely does not include the starting point. It only passes 2 parameters in the hello world example.


Thanks again.

T.
Topic archived. No new replies allowed.