-
July 2nd, 2004, 10:42 AM
#1
char to int?
what function copie char to int? i tried memcpy but it deosn work....
the char is the command line argument....
thx
-
July 2nd, 2004, 10:47 AM
#2
Code:
#include <sstream>
//...
const char *c = "123";
int i;
//...
{
std::stringstram s;
s<<c;
if((s>>i).fail()){
//error
}
}
//use i...
-
July 2nd, 2004, 10:55 AM
#3
close to how I do it:
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;
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.
-
July 2nd, 2004, 11:08 AM
#4
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;
}
Hungarian notation, reinterpreted? http://www.joelonsoftware.com/articles/Wrong.html
-
July 2nd, 2004, 01:04 PM
#5
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
|