Say I've got a string variable as part of a class. How do I strip the first two characters of that string and convert it to an integer?
example:
string order;
order = "12 5 8 1";
I have to keep it as a string for use elsewhere and cannot convert it to a cstring. How do I strip off "12" and store it as an integer? Sometimes the number could be 1 or 2 digits, but never more than two. I only ever need the first number.
Thanks!
C++ Converting part of a string object to an integer?
EDIT: I've now had a chance to try compiling this. Had, to make a change, but this works:
#include %26lt;iostream%26gt;
#include %26lt;sstream%26gt;
using namespace std;
int main()
{
string order = "12 5 8 1";
string firstTwo = order.substr(0,2);
istringstream iss(firstTwo);
int i;
iss %26gt;%26gt; i;
cout %26lt;%26lt; "The value is: " %26lt;%26lt; i %26lt;%26lt; endl;
return 0;
}
Reply:get the substring of the first two chars, and then pass them to the 'strtoint' function.
that's more of a C-based solution, maybe the STL has a better way.
Reply:use atoi() function
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment