Anyone know how to convert a char array to a single int?
char hello[5]; hello = "12345"; int myNumber = convert_char_to_int(hello); Printf("My number is: %d", myNumber);
To convert an array of strings to an array of numbers, call the map() method on the array, and on each iteration, convert the string to a number. The map method will return a new array containing only numbers. Copied! const arrOfStr = ['1', '2', '3']; const arrOfNum = arrOfStr.
char[] arr = { 'p', 'q', 'r', 's' }; The method valueOf() will convert the entire array into a string. String str = String. valueOf(arr);
There are mulitple ways of converting a string to an int.
Solution 1: Using Legacy C functionality
int main() { //char hello[5]; //hello = "12345"; --->This wont compile char hello[] = "12345"; Printf("My number is: %d", atoi(hello)); return 0; }
Solution 2: Using lexical_cast
(Most Appropriate & simplest)
int x = boost::lexical_cast<int>("12345");
Solution 3: Using C++ Streams
std::string hello("123"); std::stringstream str(hello); int x; str >> x; if (!str) { // The conversion failed. }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With