Problem in <string> class copy function

Aug 24, 2014 at 9:20am
I'm trying to copy a part of a string to an array using copy function.

Why does the following code not giving expected output?
What is the reason and how to solve it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>

using namespace std;

int main ()
{
    string str = "First Name: Abdullah";
    char fname[255];
    cout << "str is: " << str << endl;

    int n = str.find(':');

    str.copy(fname,9,n+1);   // copy to array fname, how many char to copy, starting position

    fname[n+1] = '/0';

    cout << "fname is: " << fname << endl;

    return 0;
}
Last edited on Aug 24, 2014 at 9:21am
Aug 24, 2014 at 10:27am
On line 16, '/0' should probably be '\0' and I doubt n+1 is the subscript you want to use.
Aug 24, 2014 at 10:50am
Yes '/0' should be '\0'. And I've rewritten it.
But still it shows some unexpected characters after the output.

How to solve this?
Aug 24, 2014 at 1:23pm
How to solve this?


Given the length of str and the value of n, I imagine the correct index to use on line 16 could be easily calculated.
Topic archived. No new replies allowed.