I need to convert a char* to an integer. For example:
data.SetBytFldPos(*attribute->value());
The value in the attribute class is a char*. 'SetBytFldPos" takes an int.
I need to convert a char* to an integer. For example:
data.SetBytFldPos(*attribute->value());
The value in the attribute class is a char*. 'SetBytFldPos" takes an int.
You don't convert char* to an int. You may wish to parse a decimal string. This is done by atoi(). atoi("1") == 1.
You can use atoi() function
data.SetByteFldPos(atoi(attribute->value()));
There is a simple C function called atoi which is not so good because the error handling is in best case unintuitively and easy to forget. The (C) function strtol is much better, make it a habit to prefer that one to atoi. Here is example code from the man page:
#include <stdlib.h>
#include <limits.h>
#include <stdio.h>
#include <errno.h>
int
main(int argc, char *argv[])
{
int base;
char *endptr, *str;
long val;
if (argc < 2) {
fprintf(stderr, "Usage: %s str [base]\n", argv[0]);
exit(EXIT_FAILURE);
}
str = argv[1];
base = (argc > 2) ? atoi(argv[2]) : 10;
errno = 0; /* To distinguish success/failure after call */
val = strtol(str, &endptr, base);
/* Check for various possible errors */
if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN))
|| (errno != 0 && val == 0)) {
perror("strtol");
exit(EXIT_FAILURE);
}
if (endptr == str) {
fprintf(stderr, "No digits were found\n");
exit(EXIT_FAILURE);
}
/* If we got here, strtol() successfully parsed a number */
printf("strtol() returned %ld\n", val);
if (*endptr != '\0') /* Not necessarily an error... */
printf("Further characters after number: %s\n", endptr);
exit(EXIT_SUCCESS);
}
Notice the total lack of any kind of error check for the atoi(argv[2]) conversion. Not that strtol is super simple and intuitive to check for errors either, but it is at least better.
If you need to make sure that your char* represents a valid int, you can use Boost Lexical Cast
#include <boost/lexical_cast.hpp>
try {
data.SetBytFldPos(boost::lexical_cast<int>(*attribute->value()));
} catch (bad_lexical_cast) {
// something is wrong
}
You can also write a generic "convert string-to-X template".
template <class T>
T parse(const std::string& s)
{
T out;
std::stringstream ss(s);
ss >> out;
return out;
}
Usage:
int x = parse<int>("123");
float y = parse<float>("3.14159");
There are four ways I can think of:
atoi. This might cause a compiler warning because you need an int and its return value is long.stringstream, as shown below.Code sample:
std::string str(*attribute->value());
std::istringstream myStrm(str);
int val;
myStrm >> val;
You can
// needed
#include <sstream>
// source, target
char const * p = "123";
int ival;
// conversion
std::stringstream ss(p);
ss >> ival;
Note though that we usually talk about "strings", not char*, as long as we don't mean pointers.