assigning a char pointer to string value using for loop
Ok, I'm a beginner, I'm trying to assign a char pointer to a string.
using:
1 2 3 4 5
|
for(int i=0;i<userin.length();i++)
{
*(isbn+i) = userin.at(i);
}
|
So I've tried everything I've thought of, when userin = 1-214-02031-3, but no matter what happens I still get an output at *isbn of 1111111111111.
Any advice would be greatly appreciated.
I don't see that code producing the problem you indicate. (Your code does have a problem, though -- it fails to null-terminate the
isbn string.)
Can you give us a working example program that replicates your problem?
That said, you could use the
copy() method to get the data into a c-string:
1 2 3 4 5 6 7
|
char isbn[14];
string userin;
int len = (14 < userin.length()) ? 14 : userin.length();
userin.copy( isbn, len );
isbn[len] = '\0';
|
If you currently #include <cstring>, you could use
strncpy() instead:
1 2 3 4 5 6 7
|
char isbn[14];
string userin;
int len = (14 < userin.length()) ? 14 : userin.length();
strncpy( isbn, userin.c_str(), len );
isbn[len] = '\0';
|
It doesn't really save you anything though, and the first method avoids the additional dependency on <cstring>.
Hope this helps.
Topic archived. No new replies allowed.