a little problem

i have a problem
here is the code:


#include "stdafx.h"
#include <iostream>
using namespace std;

int main()
{ char *a,*b;
int x;
b = "test1234567890123";
a=new char [10];
cin>>x;
memcpy(a,&b[x],10);
cout<<a;

return 1;

}
for x=0 this code returns:test123456(and some other funny symbols)
how can i return only :test123456

Aside from having many dangerous buffer overrun problems...

You have to null terminate the string. Make the a array 11 characters wide and set the last one to '\0'.
thank you... if you can be more explicit about the"many dangerous buffer overrun problems" i will be even more thankful:)
If the user enters a number greater than strlen(b) - 10 your memcpy will read beyond the end of the "b" string.
and what function would you recomand me for copy a nomber of char from one string to another?
Last edited on
I personally would use STL strings instead.

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

using namespace std;

int main() {
    static const string b( "test1234567890123" );
    size_t x;
    cin >> x;
    cout << b.substr( std::min( x, b.length() - 1U ),
        std::min( 10U, b.length() - x ) ) << endl;
}

Last edited on
Topic archived. No new replies allowed.