|
-
October 12th, 2003, 07:30 AM
#1
atoi in std:string
How do I perform atoi on std:string
-
October 12th, 2003, 08:19 AM
#2
Did you try std::string::c_str() method:
Code:
#include <cstdlib>
#include <string>
#include <iostream>
using namespace std;
int main()
{
string s("23");
cout << atoi(s.c_str()) << endl;
return 0;
}
-
October 12th, 2003, 09:26 AM
#3
is there a soloution without casting?
-
October 12th, 2003, 09:46 AM
#4
Originally posted by avi123
is there a soloution without casting?
What casting?
Regards,
Paul McKenzie
-
October 12th, 2003, 09:59 AM
#5
I mean without using c_str
is this an 'expensive' function?
-
October 12th, 2003, 10:14 AM
#6
In MS-STL it conditionaly returns pointer, in SGI -- just returns it.
-
October 12th, 2003, 10:39 AM
#7
so it's not expensive, right?
-
October 12th, 2003, 01:15 PM
#8
Originally posted by avi123
so it's not expensive, right?
How many times are you expecting to use c_str()? I would argue that atoi() is an "expensive" function, and c_str() adds no overhead, but that depends on the implementaion of std::string.
In any event, to get a const char * from a std::string, you must call c_str(), and this is what atoi() is expecting.
Regards,
Paul McKenzie
-
October 12th, 2003, 05:59 PM
#9
Paul
I must use atoi or eqvivalent function
I have std:string and not char *, if there is no way to do it directly on the std:string then I'll use c_cstr and then atoi,
but I must perform atoi (or similar function)
-
October 12th, 2003, 08:18 PM
#10
Originally posted by avi123
Paul
I must use atoi or eqvivalent function
I have std:string and not char *, if there is no way to do it directly on the std:string then I'll use c_cstr and then atoi,
but I must perform atoi (or similar function)
Your only choice is to use c_str(). The buffer for a std::string is not guaranteed to be contiguous, so getting a direct pointer to the buffer is not guaranteed to work. Also, the buffer for a std::string is more than likely a private member variable, therefore you don't have access to it.
An implementation of a string class (even though it isn't called std::string) called the std::rope (http://www.sgi.com/tech/stl/Rope.html)
that SGI STL supports, is an example where the characters for the string are not stored in a contiguous buffer.
Regards,
Paul McKenzie
-
October 13th, 2003, 03:47 AM
#11
so is it safe to use c_csr and then atoi?
-
October 13th, 2003, 05:04 AM
#12
Originally posted by avi123
so is it safe to use c_csr and then atoi?
Yes...
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|