what function copie char to int? i tried memcpy but it deosn work....
the char is the command line argument....
thx
Printable View
what function copie char to int? i tried memcpy but it deosn work....
the char is the command line argument....
thx
Code:#include <sstream>
//...
const char *c = "123";
int i;
//...
{
std::stringstram s;
s<<c;
if((s>>i).fail()){
//error
}
}
//use i...
close to how I do it:
You can also use boost::lexical_cast which does pretty much that above, and throws a bad_cast exception, though personally I prefer to throw my own exception with a description of what you were trying to cast to what.Code:const char * nums( "123");
std::stringstream ss( std::string( nums ) ); // simpler way
int i;
std::string garbage;
ss >> i >> garbage;
if ( !garbage.empty() )
{
// error
}
return i;
Another option to keep in mind is using the C-function atoi() which accepts a char*.
Code:#include <iostream>
#include <cstdlib>
using namespace std;
int main(int argc, char * argv[])
{ int n = atoi(argv[1]);
cout << n << endl;
}